Search code examples
c#loggingenterprise-libraryapplication-blocks

Logging Application Block - Logging the caller


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.


Solution

  • 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);
      Logger.Write(le);
    }
    

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

    Extended Properties: Called from - LAB_Demo.Tester