Sep 10 2008

Configuring log4net

Category: Programmingavinashsing @ 9:10 am

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 –>
<log4net>
<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”/>
</layout>
</appender>

<root>
<appender-ref ref=”RollingFileAppender”/>
</root>
</log4net>

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”; ;
log4net.Config.XmlConfigurator.Configure();
}

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!”);
}

Leave a Reply