Supertext Home
Chief of the System Blog

Using Log4Net for a Windows Console Application

February 11th, 2009 by

Most examples with Log4Net are with ASP.NET, but it works perfectly fine with Windows Form and Console Applications too.

What you need is an App.config file that you add to your project.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
  </configSections>
  
    <!-- Log4net Logging Setup -->
  <log4net debug="false">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="C:\\directory\\supertext_outsidetasks.log"/>
      <param name="AppendToFile" value="true"/>
      <maxSizeRollBackups value="10"/>
      <datePattern value="yyyy-MM-dd"/>
      <rollingStyle value="Date"/>
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
      <layout type="log4net.Layout.PatternLayout">
        <header value="Date | Level | SessionID | Logger | Message | &#xA;"/>
        <param name="ConversionPattern" value="%date{ABSOLUTE}| %-5p | %-30logger| %m|%n"/>
      </layout>
    </appender>
    <root>
      <priority value="DEBUG"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
  </log4net>
</configuration>

Then initialize it in your main() function:

using log4net;
using log4net.Config;


static void Main(string[] args)
{
    log4net.Config.XmlConfigurator.Configure();
    
    //your code
}

And you can use it like in ASP.NET:

log.Info("Hello Logfile");

The only issue I had was that adding the configSection like this did not work:

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

I had to add the whole shebang with Version, etc. to it. Then it started working. Anyone else had that problem?

Anyway, are people still using Log4Net? There is not much activity on the project anymore and the last version is getting pretty old.

Leave a Reply

  • Topics
  • Archive
  • Subscribe
  • Facebook
  • Twitter