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" ?>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
    <!-- 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"/>
      <priority value="DEBUG"/>
      <appender-ref ref="RollingLogFileAppender"/>

Then initialize it in your main() function:

using log4net;
using log4net.Config;

static void Main(string[] args)
    //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:

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

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.

One Comment to “Using Log4Net for a Windows Console Application”

  • Milos says on April 25th, 2014 at 9:16 am :

    Great! Thanks! It’s very useful to find short tutorials as this one, saves a lot of time!

Leave a Reply

  • Topics
  • Archive
  • Subscribe
  • Facebook
  • Twitter