Introduction
Before. NET, we were always looking for a way to log current method name in a log file for better logging. but, there were no functionalities that cocould have helped in this, and it was left as an uncompleted job.
But, with. NET, we cocould easily find out the name of the current method or parent method. This has been accomplishedStackFrame,StackTrace, AndMethodBaseClasses inSystem.DiagnosticsAndSystem.ReflectionNamespaces.
- StackFrameProvides information about function call on stack call for current process.
- StackTraceIs a collection
StackFrame.
- MethodBaseIs an abstract class containing information about current method.
Note: When an exception occurs in the method, exception object contains a reference toStackTraceObject that cocould be used to log the method name. But for logging a method name without an error generated, we need to read it from the stack, usingStackFrameClass.
In the sample,MethodBaseObject wocould reference to current function on stack call returnedStackFrameObject. To get the parent method, we wocould useStackTraceTo get parent'sStackFrameObject.
Create a new console application:
Add namespaces:
| Copy Code
using System.Diagnostics;using System.Reflection;
Create a new static function namedWhatsMyNameAnd call it fromMainFunction.
| Copy Code
[STAThread]static void Main(string[] args){ WhatsMyName();}// function to display its nameprivate static void WhatsMyName(){ stackFrame = new (); MethodBase methodBase = stackFrame.GetMethod(); Console.WriteLine(methodBase.Name ); // Displays “WhatsmyName” WhoCalledMe();}// Function to display parent functionprivate static void WhoCalledMe(){ StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); MethodBase methodBase = stackFrame.GetMethod(); // Displays “WhatsmyName” Console.WriteLine( " Parent Method Name {0} ", methodBase.Name ); }
Note: This feature is not available in. NET Compact FrameworkStackFrameClass is unavailable. For that, you wowould need to use same old method of manually passing method name to the logging function.
Http://www.codeproject.com/Articles/7964/Logging-method-name-in-NET