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:

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

then add the section itself:

      <level value="ALL" />
      <appender-ref ref="ConsoleAppender" />
      <appender-ref ref="RollingLogFileAppender" />
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date{HH:mm:ss,fff} - %message%newline" />
    <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" />

In your code do the following:

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


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 :)