Introduction to log4net

I noticed that logging is an usual requirement in our applications. And there are several ways of logging:

  1. Logging to a local file by hard coding, like using StreamWriter
  2. Logging to Windows event logs by using native classes in .NET libraries, like System.Diagnostics.EventLog
  3. Logging using third part library, like log4net

 

Each way is used according to different situations, but I’d like to briefly introduce how to use log4net to log to a file since it is easy to configure and implement:

First is to install the log4net NuGet Package:

 log4net

 

The second is to add a configSection in your App.config or Web.config file. This configuration section specifies the name, type and other properties of your logger.

The sample code is shown below:

 log4net

 

Third thing is to add a reference to log4net assembly. Simply add a using statement on top of your assembly.

The sample code is shown below:

 log4net

 

The fourth thing is to instantiate a logger interface in your classes. You have to instantiate a logger in every class in which you want to log activities.

The sample code is shown below:

 log4net

 

The fifth step is to initialize your log4net configuration.

The sample code is shown below:

 log4net

 

 

 

The last thing is to use your logger to log whatever you want.

The sample code is shown below:

 log4net

 

For more information, please refer to https://logging.apache.org/log4net/index.html.

This article was written by Joe Qian, Dynamics Technical Consultant for Tridea Partners. Tridea is a leading Microsoft Dynamics provider.