Log4Net in a Windows Forms app (quick and easy)

August 10, 2011 by: B.Harding

This post will show you how get Log4Net working ASAP on a windows forms application.

First, get Log4net.
The easiest way to do this is to open the Tools, Library Package Manager, Package Manager Console then type
Install-Package Log4Net

Next add the log4net config to your App.config.

WATCH OUT!   <configSections> must be the first child element of <configuration>

WATCH OUT!  Target the 4.0 framework. My project was defaulted to 4.0 Client Profile and would not build

<configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
     </configSections>
    <!-- Log4net Logging Setup -->
    <log4net debug="false">
        <appender name="LogFileAppender" type="log4net.Appender.FileAppender,log4net" >
            <param name="File" value="Errors.log" />
            <param name="AppendToFile" value="true" />
            <layout type="log4net.Layout.PatternLayout,log4net">
                <param name="ConversionPattern" value="%n%n%n%d [%t] %-5p %c  - %m%n%n" />
            </layout>
        </appender>
        <root>
            <priority value="ALL" />
            <appender-ref ref="LogFileAppender" />
        </root>
        <category name="DesktopLogger.Form1">
            <priority value="ALL" />
        </category>
    </log4net>

Notice this line

<param name="File" value="Errors.log" />

I left the path off. That will put the log in the same folder where the executable was run from. We could set it to

value=”c:\\temp\\Errors.log”  or what ever you need.


Now that setup is complete we have three steps to using the logger. 1.) load the configuration 2.) create a log category 3.) log something  

-----------------------

1.) Load the configuration by calling

 log4net.Config.XmlConfigurator.Configure();

on the line just before

InitializeComponent();


2.) Add the log category as a property of the form itself, not in a function


    public partial class Form1 : Form
    {
        private readonly ILog log = LogManager.GetLogger("YourAppName.Form1.cs");

3.) Log errors by calling the Error method of your log object

            int x = 10;
            int y = 10;
            try
            {
                int z= x/(y-10);
            }
            catch (Exception ex) {
                log.Error("onload", ex);
            }


Lets look at the log file entry

2011-08-10 11:07:14,584 [9] ERROR YourAppName.Form1.cs  - onload

System.DivideByZeroException: Attempted to divide by zero.
   at ProPayMigration.Form1..ctor() in C:\dev\local\ProPayMigration\ProPayMigration\Form1.cs:line 60


YourAppName.Form1.cs is the category name we set when the log is initialized

onload is the string I passed in when I called the method to create the entry

Filed under: Uncategorized

Leave a Reply

*