C# .NET: Setup log4net in a .NET Windows Console Application

6/30/2014 8:44:11 PM

The following is to setup log4net in a console application. You will need to get the log4net Nuget package or reference a downloaded log4net dll.

//AssemblyInfo.cs
...

[assembly: log4net.Config.XmlConfigurator(Watch = true)]


//App.Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<configSections>    
		<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
	</configSections>
  
	<log4net>

		<root>
			<!-- add other appenders here and the log messages will be sent to every listed appender -->
			<appender-ref ref="LogFileAppender" />

			<level value="ERROR"/>
		</root>

		<!-- The DebugFileAppender writes all messages to a log file-->
		<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
			<file value="C:\\Projects\\Logs\\iFormBuilder.log" />
			<appendToFile value="true" />
			<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%d [%t] %-5p %c %m%n" />
			</layout>
		</appender>

	</log4net>
	
	....
	
	
//Program.cs - or whatever files you have
var log4Net = log4net.LogManager.GetLogger(typeof(Program));
log4Net.Debug("Start logging.");