log4net is a fantastic library for adding configurable logging to your project. Configuration is relatively straightforward but I always get caught out when adding it to a new project.
So, here's a cribsheet for adding it in…
- Download the latest stable library, and add a reference to it within your own project
- Ensure that you have an app.config file
- Add the configSection for log4net (see samples, below)
- Add the log4net section (another sample)
- Add an ILog object to your class
- And, the bit I always forget, add the [assembly] entry to the top of your class
In your app.config file, add log4net to the <configSections> (if you don't have one of these, it goes at the next level down from the <configuration> element;
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
Next, add a log4net section. I tend to just use the following boilerplate (which gives a decent console and file appender);
<log4net>
<root>
<level value="WARN"/>
<appender-ref ref="RollingFileAppender" />
<appender-ref ref="ConsoleAppender" />
</root>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender" >
<file value="Logs/general.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="2000KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value=" [Session starts] "/>
<param name="Footer" value=" [Session ends] "/>
<param name="ConversionPattern"
value="%d [%t] %-5p %c.%M() [%x] <%X{auth}> – %m%n"/>
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] <%X{auth}> – %m%n"/>
</layout>
</appender>
<logger name="kwoloBackup.Service.Program">
<level value="WARN" />
</logger>
<logger name="theCmdb">
<level value="DEBUG" />
</logger>
<logger name="theCmdb.PacketGatherer">
<leve lvalue="INFO" />
</logger>
<logger name="theCmdb.PacketGathererService">
<leve lvalue="INFO" />
</logger>
</log4net>
And finally, add the Assembly attribute and the create a static logger object on the class you want to be logging from;
[assembly: log4net.Config.XmlConfigurator()]
namespace kwoloBackup.Service
{
static classProgram
{
private static readonly ILog log = LogManager.GetLogger("kwoloBackup.Service.Program");
static void Main(string[] args)
{
Of course, if all that doesn't mean too much to you, then do go to http://logging.apache.org/log4net/ for much more information on what log4net can do for you.