Configuring log4net

Tried Enterprise Library Logging Application Block but i’ll have to say that log4net is easier and faster to use. So here’s how to configure it. With the log4net.dll in your bin, you will need to open your web.config file and add the following line to your configSections node:

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

The after the </configSections> or anywhere else within <configuration>,

<log4net configSource=”Config\log4net.config” />

Note: I store my log4net configuration as a separate xml file in a Config folder!

Your log4net.config file should look like this:

<!-- Logging related config options below this point -->
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="%property{logpath}"/>
<param name="Threshold" value="DEBUG"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="10MB"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>

<appender-ref ref="RollingFileAppender"/>

Note 2 : I use only rolling file appender.

In my global.asax, i have this:

private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

static MyApplication()
log4net.GlobalContext.Properties["logpath"] = AppDomain.CurrentDomain.BaseDirectory + "Log\\Log.txt.not"; ;

And in the classes i want to use log4net, i have:

private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

protected void Page_Load(object sender, EventArgs e)
log.Debug("I am logging, yeh!");

What to do is log4net is not logging

Add the following key to your web.config or app.config file under appSettings:

<add key=”log4net.Internal.Debug” value=”true”/>

This will log debug messages to the Console Window and you can see what the problem is.


1. The log4net dll needs to have Copy Local to true so that it always gets put in the bin

2. The directory where the log is to be created needs to have write permissions. So check the app pool has the right access rights. IIS Express runs under the logged in user account, so this shouldn’t be a problem.

3. In global.asax file, there needs to be a call to log4net.Config.XmlConfigurator.Configure(); otherwise log4net won’t be configured properly. If this call is put in the AssemblyInfo.cs instead, this may not work for class libraries (app.config instead of web.config)

comments powered by Disqus