Logging Application Block - Logging the caller

Go To StackoverFlow.com


When logging with Log4Net it's very easy to put class that called the log into the log file. I've found in the past that this makes it very easy to trace through the code and see the flow through the classes. In Log4Net I use the %logger property in the conversion pattern like so:

<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />

And this gives me the output I want:

2008-09-19 15:40:26,906 [3132] ERROR <b>Log4NetTechDemo.Tester</b> [(null)] - Failed method

You can see from the output that the class that has called the log is Log4NetTechDemo.Tester, so I can trace the error back to that class quite easily.

In the Logging Applicaton Block I cannot figure out how to do this with a simple log call. Does anyone know how it can be done? If so, an example or steps to do so would be very helpful.

2008-09-19 06:12
by Odd


Add the calling method to the LogEntry's ExtendedProperties dictionary; assuming you haven't removed the ExtendedProperties tokens from the formatter template, of course.

Put something like this in a logging wrapper:

public void LogSomething(string msg)
  LogEntry le = new LogEntry { Message = msg };
  le.ExtendedProperties.Add("Called from", new StackFrame(1).GetMethod().ReflectedType);

Calling this produces something like this at the end of the log:

Extended Properties: Called from - LAB_Demo.Tester
2008-09-19 10:24
by lotsoffreetime


We havn't found an easy way without hitting the StackTrace. If it's an exception, we just grab from that:

 StackTrace trace = new StackTrace(ex, true);
 StackFrame frame = trace.GetFrame(0);

For chatty items, we just write the string. We have a snippet that's able to grab the class name on insertion. We also declare the const string with the class name.

Not pretty, but it's the best we've found. I hope someone else has a bettwe answer in this thread :)

2008-09-19 06:38
by Tom Carr