How to use Log4Net in C# application

log4net logo

Introduction:

Log4Net is library that you can use to manage data logging into flat files. The Log data might vary from informative messages, Diagnostics messages to Error messages and will help in debugging and troubleshooting issues on the application with out the need to debug the code line by line. The main purpose of this post is to show the minimum changes that developer needs to use Log4Net library.

You can find the Log4net library’s code on github under the following url https://github.com/apache/log4net

 

How to Install in .Net application:

1. Get the needed references in the project.

Right click the solution project that you will use the library on, and choose “Manage NuGet Packages” from the menu. this will show a new popup to search libraries.. Search for “Log4Net” then click on Install button as in below image

Log4Net image

This will add Log4Net dll reference to your project references.

2. Assembly.Info changes:

under the selected project, choose properties node and expand it. open assembly.info file and add the following line.

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

This line of code will tell Log4Net to be watching the xml configuration.

3. Adding the needed configuration to app.config or web.config file:

Open the configuration file and add the following line under the <configSections> tag

<section name=”log4net” type=”log4net.Config.Log4NetConfigurationSectionHandler, log4net” />

       

Add the following XML tag at the end of the config file but before the configuration closing tag  </configuration>

<log4net debug="true">
	<appender name="RollingFileConfig" type="log4net.Appender.RollingFileAppender">
		<file value="C:\\LogFolder\\Log.txt" />
		<appendToFile value="true" />
		<rollingStyle value="Size" />
		<maxSizeRollBackups value="1000" />
		<maximumFileSize value="1KB" />
		<staticLogFileName value="true" />
		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
		</layout>
	</appender>
 
	<root>
		<level value="ERROR" />
	</root>
	<logger name="Exceptions">
		<level value="ERROR" />
		<appender-ref ref="RollingFileConfig" />
	</logger>
</log4net>

5. Log Messages from your code:

Logging messages from the code is one line of code as below:

LogManager.GetLogger(“Exceptions”).Error(“Information to Log Goes here!”);

the parameter that is passed to GetLogger function is the same Logger name on the config file. so basically you are telling the log4net to log an exception category with level Error to file