can Log method of class A get to know who calls it ?
class A
{
public void Log(string msg)
{
Log.Write("method_name: " + msg);
}
}
I want to know a name of class and a name of a method.
You can use the StackTrace
and StackFrame
classes. You can either get a whole stack trace by calling the StrackTrace
constructor, or just a particular stack frame using the StackFrame
constructor which takes the number of frames to skip.
You should be aware that it can be inaccurate due to inlining. (e..g method A inlines method B which calls your method - method A will be reported, not B).
Sample code:
using System;
using System.Diagnostics;
class Test
{
static void ShowCaller()
{
// Use this code if you want multiple frames
// StackTrace trace = new StackTrace();
// StackFrame frame = trace.GetFrame(1);
// Use this code if you're only interested in one frame
StackFrame frame = new StackFrame(1);
Console.WriteLine(frame.GetMethod());
}
static void Intermediate()
{
ShowCaller();
}
static void Main()
{
Intermediate();
}
}
Running as an optimized release build, this will print Void Main()
- when running a debug build, or if you put more code into the Intermediate()
method, it will print Void Intermediate()
.
(As mentioned in comments, this will also create a performance hit. You should measure it to see if it's acceptable in your particular case.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With