web analytics

How to Get Calling Method Name When Exception is Logged in C#?

Options

codeling 1595 - 6639
@2016-01-15 15:19:03

Getting the calling method name can be useful when excpetion happened and you want to know which method threw the exception. 

To get name of calling method use method StackTrace.Get­Frame. Create new instance of StackTrace and call method GetFrame(1). The parameter is index of method call in call stack. Index of the first (the nearest) method call is "1“, so it returns a StackFrame of the calling method (method which directly called the current method). To get the method name use StackFrame.Get­Method (to get MethodBase) and then just get value of Name property.

The following code shows you how to write thisinformation into the log:

private void WriteLog(string message)
{
 var st = new System.Diagnostics.StackTrace();

 var methodName = st.GetFrame(1).GetMethod().Name;

 var logMessage = string.Format("{0} [{1}]: {2} [{3}()]",
   DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
   System.Threading.Thread.CurrentThread.ManagedThreadId,
   message,
   methodName);

 Console.WriteLine(logMessage);

 //Replace your real logic to write log file
 //WriteToFile(logMessage);
}

The log message shoul be like the following:

2016-01-11 23:32:52[4]: Index was outside the bounds of the array. [YourAembly.YourMethod()]

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com