rpmansion
rpmansion

Reputation: 2014

Difference between StackFrame and MethodBase when using in Logging

I have seen two separate codes that use the StackFrame and MethodBase when implementing Logging in.NET.

I know that MethodBase class provides information about methods and constructors, and where they come from. The StackFrame represents a function call on the call stack for the current thread

The first code uses the StackFrame:

StackFrame frame = new StackFrame(1, false);
var method = frame.GetMethod();
var declaringType = method.DeclaringType;

return LogManager.GetLogger(declaringType);

The second code uses the MethodBase:

var method = MethodBase.GetCurrentMethod();
var declaringTye = method.DeclaringType;
return LogManager.GetLogger(declaringTye);

Why would the first code be used and not the second code, vice-versa? In my own experience, I know that using the first code will cause an issue when you're in the release mode of your application, thus require some changes. Something like the below.

do
{
   StackFrame frame = new StackFrame(1, false);
   var method = frame.GetMethod();
   var declaringType = method.DeclaringType;
   if (declaringType == null)
   {
       loggerName = method.Name;
       break;
   }
   framesToSkip++;
   loggerName = declaringType.FullName;
} while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase));
return LogManager.GetLogger(loggerName);

Upvotes: 2

Views: 361

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190941

GetCurrentMethod won't allow you to call up the stack. Some logging implementations like to skip any internals for the logging system to make the logs more relevant.

Upvotes: 1

Related Questions