C# .NET: Setup Simple log4net File Logging

6/5/2014 8:44:20 PM

The following is a simple way to setup log4net to log actions using the file appender. You can get log4net using Nuget in Visual Studio (right-click your project references -> Manage Nuget Packages...).

If you want to create a separate file for log4net configs (ex: log4net.config), you must update your Global.asax.cs file in the Application_Start section (code at bottom).

<!-- Web.config -->
<configuration>
	<configSections>

		<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

	</configSections>

	...

	<!-- Parent Section is configuration -->
	<log4net>

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

		<!-- The DebugFileAppender writes all messages to a log file-->
		<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
			<file value="C:\\Projects\\Logs\\Testing.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>
	
	...
	
</configuration>

//C# Code
log4net.Config.XmlConfigurator.Configure();
log4net.ILog log = log4net.LogManager.GetLogger("LogFileAppender");
log.Error("Error Message");
log.Debug("Debug Message");
log.Fatal("Fatal Message");
log.Info("Info Message");
log.Warn("Warning Message");

//seperate log config file
protected void Application_Start()
{
	...

	log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));
}