12132866_sAll programs should be able to log. With log4net this is made easy. Start with this great tutorial.

Quick guide:

log4net has a lot of settings and features. This sample shows how to log to a simple text file with some default settings

1. Use NuGet to install log4net in your project

2. In the App.config file, add this section of code:

<?xml version="1.0"?>
 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

 <!-- levels: ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF -->
 <level value="INFO" />
 <appender-ref ref="FileAppender" />

<appender name="FileAppender" type="log4net.Appender.RollingFileAppender, log4net" >
 <param name="File" value="Log.txt" />
 <param name="AppendToFile" value="false" />
 <param name="maximumFileSize" value="200KB" />
 <param name="maxSizeRollBackups" value="1" />

<layout type="log4net.Layout.PatternLayout, log4net">
 value="%date{yyyy.MM.dd hh:mm:ss} %-5level [%thread] - %message%newline" />


3. You need 3 lines of code

First, just below the using statements

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

Then in every class, add this line

private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Now you are ready to log

log.Info("Hello World");


Leave a Reply

Your email address will not be published. Required fields are marked *