In a recent project, I needed to implement logging and decided to use the log4net.dll which I have seen referenced in a number of different open source projects. Here are the steps I had to taken in order to use log4net in my project:
1. Download the log4net.dll from http://sourceforge.net/projects/log4net/
2. Add a reference to your project that includes the downloaded log4net.dll
3. Add a log4net section to your web.config/app.config file:
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
</sectionGroup>
</configSections>
</configuration>
4. Add a log4net.config file to your project with the following configuration:
<?xml version="1.0" encoding="utf-8"?>
<log4net debug="true">
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="log4netoutput.log" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p [%c] %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
There are various Appenders you can create but this example uses a text file to log the results into the bin directory of the application. There are also different values that can be used as part of the ConversionPattern to get different output.
5. Be sure to change the properties of the log4net.config file in your project for the Copy to Output Directory attribute to Copy Always. I spent hours debugging my code because the config file was not being copied into the bin directory and log4net did not throw any exceptions. Since I had not used log4net before, I was making the assumption the problem was with my code and/or config file settings.
6. Here’s my code from a test method to make sure log4net is working correctly:
[Test]
public void TestLog4NetOnItsOwn()
{
ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
XmlConfigurator.Configure(new FileInfo(Settings.Default.log4net_config_file));
logger.Debug("Here is a debug log.");
}
To log results to the console, include the following line of code:
BasicConfigurator.Configure();
I’ve seen other posts that reference the log4net.config file in the Assembly.cs file rather than in code:
[assembly: log4net.Config.XmlConfigurator(ConfigFile="log4net.config", Watch = true)]
Other Posts and Resources:
http://it.toolbox.com/blogs/daniel-at-work/using-log4net-in-cnet-26794
http://geekswithblogs.net/bsherwin/archive/2008/02/15/119657.aspx