Log4net logging
Assembly attribute
In Properties/AssemblyInfo.cs or alongside it.
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
Console startup
class Program
{
private static readonly ILog Logger = LogManager.GetLogger(typeof(Program));
static void Main(string[] args)
{
XmlConfigurator.Configure();
Configure and watch:
log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net.xml"));
Website startup
Web activator helps.
[assembly: WebActivator.PreApplicationStartMethod(typeof(Web.App_Start.LoggingConfig), "PreApplicationStart")]
namespace Web.App_Start
{
public static class LoggingConfig
{
public static void PreApplicationStart()
{
log4net.Config.XmlConfigurator.Configure();
}
}
}
Configuration
Config section if in App/Web.config:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
Logging to two different roll-over file appenders by level.
<log4net>
<root>
<level value="WARN" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="ErrorFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString">
<conversionPattern value="..\logs\website\Log.log" />
</file>
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<staticLogFileName value="false" />
<preserveLogFileNameExtension value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
</layout>
</appender>
<appender name="ErrorFileAppender" type="log4net.Appender.RollingFileAppender">
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR" />
<acceptOnMatch value="true" />
</filter>
<file type="log4net.Util.PatternString">
<conversionPattern value="..\logs\website\Errors.log" />
</file>
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<staticLogFileName value="false" />
<preserveLogFileNameExtension value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
</layout>
</appender>
</log4net>
- To preserve the file extension (rather than ".1"): <preserveLogFileNameExtension value="true" />