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
, AndMethodBase
Classes inSystem.Diagnostics
AndSystem.Reflection
Namespaces.
- 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 toStackTrace
Object 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, usingStackFrame
Class.
In the sample,MethodBase
Object wocould reference to current function on stack call returnedStackFrame
Object. To get the parent method, we wocould useStackTrace
To get parent'sStackFrame
Object.
Create a new console application:
Add namespaces:
| Copy Code
using System.Diagnostics;using System.Reflection;
Create a new static function namedWhatsMyName
And call it fromMain
Function.
| 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 FrameworkStackFrame
Class 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