log4net and Visual Studio 2005 — quick and easy

So you have an ASP.NET application and want to do some custom logging other than by using Response.AppendToLog(). Or maybe you have a console app that you want to log what it’s doing. Good! Let’s get you set up using log4net (a very popular logging library) in a few minutes so you can start keeping track of things. Much of this is based on Haacked’s Quick and Dirty Guide to log4net, which is based on VS2003 but still a good read. I also got some tips for Visual Studio 2005 from Akash’s blog. Now let’s get started.

Download log4net

Download and extract the latest stable release of log4net here.

Add a reference

In your Visual Studio project, add a reference (Project->Add Reference) to log4net.dll (in the binnet<dotnet version>release directory where you extracted the log4net zip file).

Add a log4net config file

Even though you can add log4net configuration settings to your app’s main .config file, we’re going to give log4net it’s own config file for two reasons: 1) cleanliness, and 2) you can log4net change the config settings on the fly without having to restart the app. 🙂

So, create a new .config file in the root directory of your application ad name it log4net.config. If you’re building a client app, set the “Copy to Output Directory” property to “Copy Always”. Remove everything in the log4net.config file, and paste the below XML into it.  It contains sample configurations to log many types of events (info, warning, error, fatal) to a rolling set of log files in a “log4net” subdirectory in your application’s root directory. It will also send emails for any error or fatal events. You’ll at least want to change the Smtp settings to a valid host & email account.

<?xml version=“1.0”?>
<log4net>
    <appender name=“SmtpAppender” type=“log4net.Appender.SmtpAppender”>
        <to value=“support@yourcompany.com” />
        <from value=“support@yourcompany.com” />
        <subject value=“ERROR on site” />
        <smtpHost value=“your.smtp.host” />
        <bufferSize value=“256” />
        <lossy value=“true” />
        <evaluator type=“log4net.spi.LevelEvaluator”>
            <threshold value=“ERROR” />
        </evaluator>
        <layout type=“log4net.Layout.PatternLayout”>
            <conversionPattern value=“%-5p %d [ThreadId: %t] Class:%c{1} Method:%M %nMESSAGE:%n%m%n%n” />
        </layout>
    </appender>
    <appender name=“RollingLogFileAppender” type=“log4net.Appender.RollingFileAppender”>
        <file value=“log4net\logfile.txt” />
        <appendToFile value=“true” />
        <datePattern value=“yyyyMMdd” />
        <rollingStyle value=“Date” />
        <filter type=“log4net.Filter.LevelRangeFilter”>
            <acceptOnMatch value=“true” />
            <levelMin value=“INFO” />
            <levelMax value=“FATAL” />
        </filter>
        <layout type=“log4net.Layout.PatternLayout”>
            <conversionPattern value=“%-5p %d %5rms %-22.22c{1} %-18.18M – %m%n” />
        </layout>
    </appender>
    <root>
        <level value=“DEBUG” />
        <appender-ref ref=“SmtpAppender” />
        <appender-ref ref=“RollingLogFileAppender” />
    </root>
</log4net>

Initialize the configuration

If you’re using a web application, add the following line to your Application_Start method in global.asax.

log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(Server.MapPath(“log4net.config”)));

If you’re using a client application (e.g. a console app), add the following line to your app’s initialization routine:

log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(“log4net.config”));

These lines tell log4net to load configuration information from the local log4net.config file and watch it for any configuration changes while the app is running.

Start logging

Now wherever you want to log some information in a particular class, add a member variable like this

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

This creates a logger variable, and causes log messages to be prefixed with the class name containing the logger variable. That makes it easier to sift through logs, since you’ll be able to see which messages came from which classes.

Then when you want to do some logging you can just use statements like this

logger.Info(“some info”);
logger.Warn(“a stern warning!”)
logger.Error(“An error occurred!”);

Reading the logs

The sample config (above) creates a log file named logfile.txt in a log4net subdirectory inside your application’s root directory. Note that for client applications, that’ll be your bin/debug or bin/release folders (or wherever the EXE lives). Since we used a RollingLogAppender, older logs will be archived with the date apprended to the file name. That means that “logfile.txt” only contains messages for the current day.

Deploying your app

When you deploy your application, make sure to deploy the log4net.dll, log4net.xml, and log4net.config files. Also make sure that your application’s account (e.g. the ASPNET account for web apps, or the user for client apps) can create and write to the “log4net” subdirectory. For web applications you may want to go ahead and create the “log4net” subdirectory up front and assign ASPNET full control rights to that.

Tweaking the configuration

You can tweak the settings in your log4net.config at any time, even while the app is running. You may wish to change the location of the log file, or add different appenders, or change what type of messages get logged. I suggest reading the log4net documentation for more information.

 

 

 

0