Can a method know the name of the calling class & method?

S

ssg31415926

I want to write a logging method. I want it to log the name of the
calling class and method. Is there any way to do this? I presume
it'll use Reflection but it's not an area I've used much.a

Alternatively, is there a piece of code I can use to pass in the name
of the method, so that I can copy and paste the calling code and don't
have to remember to change a hard coded method name.

I could code this:

Log("callingClass.CallingMethod", someData, someLogCode);

but I'd rather code this:

Log(someData, someLogCode); and have it work out what the calling
method was.

or at least, this:

Log(System.Reflection.Blah.CurrentMethod, someData, someLogCode);

Merry Christmas!

SSG
 
T

Tim Van Wassenhove

ssg31415926 schreef:
I want to write a logging method. I want it to log the name of the
calling class and method. Is there any way to do this? I presume
it'll use Reflection but it's not an area I've used much.a

Alternatively, is there a piece of code I can use to pass in the name
of the method, so that I can copy and paste the calling code and don't
have to remember to change a hard coded method name.

I could code this:

Log("callingClass.CallingMethod", someData, someLogCode);

but I'd rather code this:

Log(someData, someLogCode); and have it work out what the calling
method was.

or at least, this:

Log(System.Reflection.Blah.CurrentMethod, someData, someLogCode);

Log(MethodBase.GetCurrentMethod().DeclaringType,MethodBase.GetCurrentMethod().Name);
 
D

Duggi

Use log4Net :) Its a well known log utility. (open source)

Once you use it, you will never try to write a log class.

Thanks
-Srinivas.
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

ssg31415926 said:
I want to write a logging method. I want it to log the name of the
calling class and method. Is there any way to do this? I presume
it'll use Reflection but it's not an area I've used much.a
but I'd rather code this:

Log(someData, someLogCode); and have it work out what the calling
method was.

MethodBase m = (new StackTrace()).GetFrame(1).GetMethod();
string classname = m.DeclaringType.Name;
string methodname = m.Name;

but I have serious doubt that performance will be good.

Arne
 
S

ssg31415926

Thank you all for your suggestions. I'll have a look at each and see
which fits best.

Regards

SSG
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top