StackFrame: my C# method name logging friend

Posted: 2009-11-04 in .Net

If you have the need in C# to get the calling method name, then use System.Diagnostics StackFrame.
Stack frame has a ton of useful debugging goodies, including line numbers, columns, calling assemblies, etc.

A quick example

//Get the method name of the caller (its two up, this plus the public)

StackFrame debugginInfo = new StackFrame(2);
string methodName = debugginInfo.GetMethod().ReflectedType.Name + "." + debugginInfo.GetMethod().Name;
raiseMessage = methodName + ": " + message;

This code is a small excert from my little static logger friend. If the caller passes in a debug log then the calling class and method name is prefixed to the logged message. The reason the 2 is passed in is because this is a private method (1) and is called from several overloaded public methods (+1 = 2).
Its a very clean ,very good solution when stack tracing a client log, without relying on the log caller to pass in descriptive location information.


What do blind people dream about

  1. […] In a previous post of mine I was super excited about using the stackframe for log tracing of calling methods stackframe […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s