Using Log4Net Logging Utility


In this blog post I’m going to show you how to use Log4Net.  Log4Net is a logging library that you can add to an application in order to log errors, warnings and informational messages.  Your log can be a file on your hard drive or messages can be sent to an email address.

The Basics

If you’re building software that will run on a web server or as a service on a server to process data, you’re going to want some sophisticated logging.  Logging can give you clues as to how your software is performing, it can indicate if there were errors and you can log information so that you can trace back and find out what your program did before it crashed (assuming it crashed).  If you have many systems, then you’ll probably want one central location where you can gather logs and the easiest way to do that is to setup logging to send emails to a debug email account.  Then you can setup filters to sort your log errors by system.  Once you look at the emails you’re receiving from your logger you can see if something is going wrong once in a while, or if your system is going crazy just by the rate at which your error emails are arriving.

Setting up Log4Net

You can install Log4Net from NuGet.  Just go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution.. and type in “log4net” in the search box.  Then install the Log4Net package.

Next you’ll need to setup your app.config file.  This file is where all the magic occurs.
First, you’ll need a line at the top that tells your application that a log4net configuration follows:

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

Next, you’ll need to define one or more “appenders”.  These are definitions for each output you want your errors to go to.  You can setup an appender to go to your console window and configure it special for a colored display.  You can setup an appender for your log which can be stored on a local hard drive.  You can setup an appender for an email address to send an email for each error/warning that occurs.  If you set up more than one appender then each source will receive error messages.

Here’s an example of a log file appender that you can copy and paste into your app.config file:

    <appender name=”RollingLogFileAppendertype=”log4net.Appender.RollingFileAppender“>
        <file value=”C:logsLog4NetDemoApplicationLogFile.txt” />
        <appendToFile value=”false” />
        <rollingStyle value=”Size” />
        <maxSizeRollBackups value=”3” />
        <maximumFileSize value=”50MB” />
        <layout type=”log4net.Layout.PatternLayout“>
            <conversionPattern value=”%date [%thread] %-5level %logger%newline%message%newline%newline” />

To make this work, you’ll need a root element block to reference this appender (put this before the last log4net tag:

    <level value=”DEBUG” />
    <appender-ref ref=”RollingLogFileAppender” />

I’m going to discuss what all this means in a minute, but let’s get this thing up and running first, so you can see something happen.  In your Program.cs file add a using for “log4net” and then replace your program with something like this:

class Program
    private static ILog log = LogManager.


    static void Main(string[] args)

        log.Info(“Program initialize“);


    static void DoSomethingBad()
            throw new ArgumentException();
        catch (Exception ex)

Now you can run your program and observe that a c:logs directory was created on your PC (if you didn’t have one already).  Inside that directory is a file titled: Log4NetDemoApplicationLogFile.txt.  If you run your program again, you’ll see another file.  with the same file name but a “.1” after it.  If you continue to run your console application, you’ll a file added each time with a “.2”, then a “.3” etc.  What’s happening here is that the first file is renamed with a “.1” after it and then a new file with only the “.txt” extension is created.  That is always the latest log file.  The remaining files will be incremented by one each time a new log file is created causing them to shift down in your directory list. 

If you look at the appender block above you’ll see a setting called “maxSizeRollBackups”.  You can set this to the maximum number of files you wish to save.  In this example it’s set to 3.  So the last file in your logs directory will end with a “.3”.  If you start your file after that, then all files will shift down and the last “.3” file will disappear.

The “appendToFile” setting means that you can append to the existing file.  In this example we create a new file every time we restart the application, but you can just append to an existing file until it reaches it’s maximum size.

The maximum size of the file can be set using the “maximumFileSize” setting.  When the log file reaches this size, a new file will be created.  This sample is set to 50 megabytes.

The layout conversion pattern allows you to define what you want to display in your error message.  You can customize this to include things like the thread number (or leave it out if you don’t care), the date, etc.

The Colored Console Appender

Now, let’s add an appender to report log entries on the console itself.  Copy this after your first <log4net> tag:

<appender name=”ColoredConsoleAppendertype=”log4net.Appender.ColoredConsoleAppender“>
        <level value=”DEBUG” />
        <foreColor value=”White” />
        <level value=”INFO” />
        <foreColor value=”Green” />
        <level value=”WARN” />
        <foreColor value=”Yellow, HighIntensity” />
        <level value=”ERROR” />
        <foreColor value=”Red, HighIntensity” />
        <level value=”FATAL” />
        <foreColor value=”White” />
        <backColor value=”Red, HighIntensity” />
    <layout type=”log4net.Layout.PatternLayout“>
        <conversionPattern value=”%date [%thread] %-5level %logger%newline%message%newline%newline” />

You’ll  also need to add this to your root block:

<appender-ref ref=”ColoredConsoleAppender” />

Now if you run your program, you’ll see error logging in your console as well as the log file.  You can alter which colors represent each type of logging.

The SMTP Appender

As I mentioned earlier, you can add an appender to send log entries to an email location.  Here’s an example email or SMTP appender that will send log messages that are errors:

<appender name=”SmtpAppenderErrortype=”log4net.Appender.SmtpAppender“>
    <to value=”” />
    <from value=”” />
    <subject value=”Export Notification – Error” />
    <smtpHost value=”” />
    <bufferSize value=”512” />
    <lossy value=”true” />
    <evaluator type=”log4net.Core.LevelEvaluator“>
        <threshold value=”ERROR” />
    <filter type=”log4net.Filter.LevelRangeFilter“>
        <levelMin value=”DEBUG” />
        <levelMax value=”FATAL” />
        <acceptOnMatch value=”true” />
    <layout type=”log4net.Layout.PatternLayout“>
        <conversionPattern value=”%property{log4net:HostName} :: %level :: %message %newlineLogger: %logger%newlineThread: %thread%newlineDate: %date%newlineNDC: %property{NDC}%newline%newline” />

After you paste the above code into your <log4net> block you’ll also need a reference for this block:

<appender-ref ref=”SmtpAppenderError” />

Now you need to doctor some values in the appender block.  Change the “to” email address to your email address.  You’ll need an smtp server address to relay your emails (smtpHost). Then you can run your program and see error messages go to your in-box.

Download Sample File

You can download the sample file here:



Leave a Reply