Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get log4net to append the real class name and not the generated closure class name?

Tags:

c#

log4net

I have a class that is logging from an anonymous method. I've dumbed it down to make the point...

public class SocketFlusher
{
    private static readonly ILog Log = LogManager.GetLogger(typeof(SocketFlusher));

    public void Flush()
    {
        Wait.For(timeout, () => 
        {
            ... // work
            Log.DebugFormat("{0} bytes available", socket.Available);
        }
    }
}

My log4net configuration is good (I've checked the log4net debug="true" output and the appender does work). My appender layout is

  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%-4thread] %-5level %class{1} - %message%newline"/>
  </layout>

But, my log output has that crazy auto-generated static class in it.

2011-03-21 18:10:20,053 [5   ] DEBUG SocketFlusher+<>c__DisplayClass1 - 82 bytes available

I want it to say SocketFlusher, what is the right appender layout to get this format?

like image 571
Anthony Mastrean Avatar asked Apr 18 '11 16:04

Anthony Mastrean


People also ask

Is log4net dependent on log4j?

Log4net is a logging utility for . NET applications. It's based on log4j, which is for Java applications. Log4net is highly configurable, so you can use it in many scenarios.

What are log4net Appenders?

For log4net to know where to store your log messages, you add one or more appenders to your configuration. An appender is a C# class that can transform a log message, including its properties, and persist it somewhere. Examples of appenders are the console, a file, a database, an API call, elmah.io, etc.

What are the main components of log4net briefly describe how loggers work in log4net?

Log4net has three main components: loggers, appenders and layouts. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.


1 Answers

You want the class name to appear in the appender output. And you're following the log4net idiom of naming your logger the name of the class...

private static readonly ILog Log = LogManager.GetLogger(typeof($CLASSNAME$));

What you want to do in the appender pattern layout is to include the %logger name pattern instead of the %class pattern.

<layout type="log4net.Layout.PatternLayout">
  <conversionPattern value="%date [%-4thread] %-5level %logger{1} - %message%newline"/>
</layout>
like image 88
Anthony Mastrean Avatar answered Sep 19 '22 09:09

Anthony Mastrean