Who is calling me? The *69 service in .NET


I recently started a project where I needed to add logging to an existing codebase. One of the requirements is that the class and method is logged along with the severity, message, exception (if there is one), date and time, etc, etc, etc. It started out not looking pretty with constants added to each class for just the class name or writing out typeof(blah).FullName and the method name each and every time, a message needed to be logged. I figured there had to be better way and parsing Environment.StackTrace (type string) didn’t seem to be it.

Looking through System.Diagnostics, I stumbled upon the StackTrace class and from there it was a skip, hop and a jump to figure out how to unwind the stack and get the information I needed.

StackTrace stackTrace = new StackTrace(1); //skip at least this frame
for (int frameCounter = 0; frameCounter < stackTrace.FrameCount; frameCounter ++)
{
    StackFrame frame = stackTrace.GetFrame(frameCounter);
    MethodBase method = frame.GetMethod();

    Console.WriteLine("Class: {0}, Method: {1}",
        method.DeclaringType.FullName,
        method.Name);
}

Simples.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Live

Tags: , ,

One Response to “Who is calling me? The *69 service in .NET”

  1. josh declore says:

    Very great submit. I just stumbled upon your web site and wanted to say that I’ve actually enjoyed reading your web site posts. Any way I’ll be subscribing for your feed and I hope you submit once more soon.

Leave a Reply