Simple Log4Net Install and Usage

By | August 11, 2016

Click Project -> Mange NuGet Packages

Choose NuGet in Package Source.

Search for Log4Net

Choose Log4Net and Install

Add one line to Project->Properties->AssemblyInfo.cs. This line will path to the Log4Net.xml config file.


[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.xml", Watch = true)]

Add new xml item to the project called log4net.xml (or whatever you called it above)

Here is a sample config file:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="RollingLog" />
<appender-ref ref="CurrentLog" />
</root>

<appender name="CurrentLog" type="log4net.Appender.FileAppender">
<file value="application.log" />
<appendToFile value="false" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %logger - %message%newline" />
</layout>
</appender>
<appender name="RollingLog" type="log4net.Appender.RollingFileAppender">
<file value="rolling.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

File the xml file’s properties to “Copy to Output Directory” : “Copy Always”

Add this as a global variable:


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

Now you are ready to use Log4Net.


log.Error("Error Message");

Leave a Reply

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