简体   繁体   中英

How to improve code for get calling method in C#

We have a "logger" class which have log method that get the log message, and wrote to the log the message and the calling method, first we did the following also to send to the log method new parameter Method.Base.GetCurrentMethod() . I found another way, to use Relection.MethodBase:

public void Log(string message)
{
   stackTrace = new StackTrace();
   string methodName = stackTrace.GetFrame(1).GetMethod().Name;
   ....
}

But I've a problem, that every calling for the log method, I forced to create new instance from StackTrace , and when I trying to create the instance in the constructor, I get that the method name is InvokeMethod .

We're using MEF in our project. Any ideas how to improve the code?

If you are using the latest and greatest version of C# (5), this is built into the language via call-site attributes. You would use it like this:

public void Log(string message, [CallerMemberName] string methodName = null)
{
}

You call the method without supplying the second parameter, and the C# compiler will automatically fill it in for you. You have the following Call-Site attributes at your disposal: CallerMemberName , CallerLineNumber and CallerFilePath .

I suggest to use the full stack trace for "Info logs" (Logs with no exception details), using

StackTrace stackTrace = new StackTrace(true); 
string stackTraceString = stackTrace.ToString();

Will give you the full stack trace with source information.

But when you have logs that have exception instance, such as logs in the catch statement, you can use the stack trace and the inner exception information of the exception itself, rather than the calling method only.

StackTrace stackTrace = new StackTrace(ex, true); 
string stackTraceString = stackTrace.ToString();

While (ex) is the exception that you need it's stack trace.

* EDIT *

Or You can use:

Environment.StackTrace, it is a string property! but contains the call of the get_StackTrace, you can write a simple code to delete this part, but I think it is Ok to make stack trace objects as you want, and it wouldn't be a big deal.

Before implementing your solution, you should be aware of Method Inlining.

Take a look at this article by Scott Hanselman, where he tries to implement almost the same feature. Some more info here

You can use PostSharp for that purpose. Take a look on this page for an example of how to improve your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM