C# Tutorial for log4net

Here’s a short tutorial on how to use log4net in C#

1. Get log4net from the apache website.

2. Open your project with visual studio.

3. Add the reference to your project: You find the reference in the zip that you just downloaded: \bin\net\xxx\release\log4net.dll. xxx is your.net version.

4. Add the  section to your app.config. The following code uses a file for the logging:

<configuration>
 <configSections>
 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
 </configSections>
 <log4net>
 <root>
 <level value="DEBUG" />
 <appender-ref ref="LogFileAppender" />
 </root>
 <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
 <param name="File" value="log-file.txt" />
 <param name="AppendToFile" value="true" />
 <rollingStyle value="Size" />
 <maxSizeRollBackups value="10" />
 <maximumFileSize value="10MB" />
 <staticLogFileName value="true" />
 <layout type="log4net.Layout.PatternLayout">
 <param name="ConversionPattern" value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
 </layout>
 </appender>
 </log4net>
</configuration>

5. Use the following code to use the configuration you just added to app.config:

static void Main
{
 log4net.Config.XmlConfigurator.Configure;
...

6. To log use the following code:

using log4net;
...
private static readonly ILog log = LogManager.GetLogger(typeof(Bar));
log.Debug("thishe first log message");
...

7. If Visual studio doesn’t recognize log4net. Configure your project like this:

Visual Studio -> project -> project name properties -> target framework ->.net Framework (not client)

This article is part of the GWB Archives. Original Author: gwbarchive

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.