Search This Blog

Tuesday, September 11, 2012

log4net quickstart; log4net FileAppender not working in ConsoleApplication

To quickly set up log4net logging in you application open you app.config file:

Add a section for log4net:


<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" requirePermission="false"/>
  </configSections>

then add the section itself:


<log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="ConsoleAppender" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date{HH:mm:ss,fff} - %message%newline" />
      </layout>
    </appender>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="c:\a\xx.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="500MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
      </layout>
    </appender>
  </log4net>

In your code do the following:

XmlConfigurator.Configure();
ILog logger = LogManager.GetLogger(typeof(Program));

logger.Info("a");

WARNING:
Do not use: BasicConfigurator.Configure(); as it does not work with this example.
Normally you'd declare a private variable for logging:

private static readonly ILog logger = LogManager.GetLogger(typeof (Program));


No comments:

Post a Comment

If you like this post, please leave a comment :)