How to use Log4Net in C# application

log4net logo


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


How to Install in .Net application:

[spacer height=”20px”]

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.

[spacer height=”20px”]

2. Assembly.Info changes:

under the selected project, choose properties node and expand it. open 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.

[spacer height=”20px”]

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" />
		<level value="ERROR" />
	<logger name="Exceptions">
		<level value="ERROR" />
		<appender-ref ref="RollingFileConfig" />

[spacer height=”20px”]

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

[spacer height=”100px”]