How to work your way through log4net?

Log4net is an open source library and by using this library any .net application can write a log to different sources (i.e text file, console, database, event Log etc.).  log4net provides a mechanism for logging information to multiple destination or sources. It provides five different level of logging, i.e.

  1. Debug
  2. Information
  3. Warning
  4. Error
  5. Fatal

The amount of information logged by each level will decrease as you go down the list. For example,  in the application development stage, we would want all information to be logged, and therefore, we can enable all the levels. When we deploy the application it is up to us, to ensure what kind of data we would like the application to log, and based on that we can enable the levels in the configuration.

How to get Log4net library and add the same to the project

  1. Right click on your project
  2. Click on “Manage NuGet Packages” option
  3. Click on “Online” section in left hand panel
  4. Type log4net in search box in the right side panel
  5. You will see the log4net install option, as shown below
  6. Click on log4net option and click on install
  7. After successful installation, you can see that log4net refence has been added in the References folder as shown below

How to use log4net in the application

Step 1 : Add the entry into AssemblyInfo.cs

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

Step 2 : Configuration changes in App.config

Add log4net section in configSections. And then add configuration for the log4net section as shown below.

<?xml version="1.0" encoding="utf-8" ?>
 <configuration>
 <configSections>
 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
 </configSections>
 <log4net>
 <appender name="LogFileAppender"
 type="log4net.Appender.RollingFileAppender" >
 <param name="File" value="E:TempLoglog.txt" />
 <param name="AppendToFile" value="true" />
 <rollingStyle value="Size" />
 <maxSizeRollBackups value="2" />
 <maximumFileSize value="10MB" />
 <staticLogFileName value="true" />
 <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
 <layout type="log4net.Layout.PatternLayout">
 <param name="ConversionPattern"
 value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %c %m%n" />
 <conversionPattern
 value="%date %level %logger %message %newline" />
 </layout>
 </appender>
 <root>
 <level value="ALL" />
 <appender-ref ref="LogFileAppender" />
 </root>
 </log4net>
 <startup>
 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
 </startup>
 </configuration>

Step 3 : Create one central logging class

public static class Logger
 {
 private static log4net.ILog Log { get; set; }
 static Logger()
 {
 Log = log4net.LogManager.GetLogger(typeof(Logger));
 }

public static void Debug(object msg)
{
Log.Debug(msg);
}
public static void Warning(object msg)
{
Log.Warn(msg);
}
public static void Error(Exception ex)
{
Log.Error(ex.Message, ex);
}
public static void Info(object msg)
{
Log.Info(msg);
}
public static void Error(object msg)
{
Log.Info(msg);
}
public static void Fatal(object msg)
{
Log.Fatal(msg);
}
}

Step 4 : Call logger method anywhere from the application

static void Main(string[] args)
 {
 Logger.Debug("This is debug log..");
 Logger.Info("This is info log..");
 Logger.Warning("This is warning log..");
 Logger.Error("This is error log..");
 Logger.Fatal("This is fatal log..");
 }

After performing the above steps , if you run the application, you will get below information logged in the log file.

2016-02-20 19:58:55,042 DEBUG Log4netSample.Logger This is debug log..
 2016-02-20 19:58:55,058 INFO Log4netSample.Logger This is info log..
 2016-02-20 19:58:55,058 WARN Log4netSample.Logger This is warning log..
 2016-02-20 19:58:55,058 INFO Log4netSample.Logger This is error log..
 2016-02-20 19:58:55,058 FATAL Log4netSample.Logger This is fatal log..

After going through these easy steps to use log4net, I would like to  give you some more details on different components in log4net.

Logger, Appender and layouts are the three main components in log4net.

Logger : Loggers are the named entities, which will basically help to write the log to different sources like text file, console, database etc.

log4net.LogManager.GetLogger(typeof(LoggerTest)) – This creates the logger for LoggerTest class. It does not mean that we have to use different logger for each class. It is up to us, how we want our application to log. If we want different sections to log in different ways, then we can use different loggers for different sections.

Loggers provide different levels of logging – All, Debug, Information, Warning, Error and Fatal.

Appenders : Using Log4net, we can log to multiple destinations. In log4net terms, output destination is called an appender. Appenders must implement log4net.Appenders.IAppender interface.

There are several appenders defined in log4net package. Some of them are FileAppender, AdoNetAppender, ConsoleAppender, EventLogAppender, RollingFileAppender , SmtpAppender and so forth.

Layouts : More often than not, users not only customize the output destination but also the output format. This can be done by associating layout with appender. Layout formats the information as specified in the configuration section of the apender.

Layout – this is one of the section in appender configuration, where user can customize the output format.

Author

  • Vidya is currently working as a Senior Software Engineer in Trigent. She has over 8 years of experience in .NET platform.