In this tutorial I am going to introduce some basic steps to implement log4net in windows service.
Step 1: Open nuget package manager and type log4net in the search box.
After install the log4net nuget package you can see the log4net dll reference in References folder of your project like below screen.
Step 2: Add the following line in your web.config file.
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="D:\\LogTest.txt" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="[Header]\r\n" />
<param name="Footer" value="[Footer]\r\n" />
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="[Header]\r\n" />
<param name="Footer" value="[Footer]\r\n" />
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="ConsoleAppender" />
</root>
</log4net>
Step 3: Now Initialize the log4net object in your service class and add "DOMConfigurator.Configure()" in the static constructor of the service class.
public partial class Service1 : ServiceBase
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
static Service1()
{
DOMConfigurator.Configure();
}
public Service1()
{
log.Info("Service Initialized.");
InitializeComponent();
ProcessAPI();
}
}
Step 4: Now you can start writing the logs into you log file. In the above example I have set the log file path to "D:\\LogTest.txt". All the logs will be saved in this LogTest.txt file under D drive.
For write the logs you need to use the log4net object that we initialized in previous step. Following line is responsible to write the logs in the text file.
log.Info("Service Started.");
hello,
ReplyDeleteThanks, sommetimes you need to add
log4net.Config.XmlConfigurator.Configure();
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
Hi Tof,
DeleteThank you very much for this information. I will test the above code and put in my article. I really appreciate your comment :).