Reputation: 2639
How to configure a .NET console application to use a rolling log file and be able to clear its contents when the application is running?
I am answering my own question after having gathered all the needed pieces by searching the web and going through the log4net documentation (which is quite chatty) once again. I tend to do this same job once in a year or two because surprisingly there is still no single answer covering all the requirements existing on SO.
Upvotes: 3
Views: 1007
Reputation: 2639
a) install NuGet package log4net (currently 2.0.x)
b) add the following line to the beginning of the Start method
public static void Start(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
...
}
c) add the following sections to App.config
*log4net sdk documentation is quite useful when trying to figure out the meaning of all these configuration values
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="RollingFileAppender_All" type="log4net.Appender.RollingFileAppender">
<file value="MyApplication.log" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message %exception%newline" />
</layout>
</appender>
<root>
<level value="ALL" /> <!-- ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF -->
<appender-ref ref="RollingFileAppender_All" />
</root>
</log4net>
</configuration>
d) create a logger instance and use it
using log4net;
public class SomeClass
{
private static readonly ILog log = LogManager.GetLogger(typeof(SomeClass));
public void DoSomething()
{
try
{
throw new InvalidOperationException("test");
}
catch (Exception ex)
{
log.Error(ex);
}
}
}
Upvotes: 5