Set up log4net for a .Net project

One of the things you should always do when setting up a .Net web project is to add the logging suite log4net. I know I do, and every time I’m having trouble figuring out how, so this is a not to myself:

1. Install log4net using NuGet.

2. Add to AssemblyInfo.cs:

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

You might have to add one per csproj if you have more than one project involved.

3. Create the file log4net.config in the root with this content:

	<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
		<file value="C:templogMyLogFile.txt" />
		<appendToFile value="true" />
		<maximumFileSize value="1024KB" />
		<maxSizeRollBackups value="20" />
		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%date %level %logger - %message%newline" />
		<level value="DEBUG" />
		<appender-ref ref="RollingFile" />

4. Add to any class where you with to use logging:

private static readonly ILog log = LogManager.GetLogger(typeof(MyClass));

5. Log!


Happy logging!