Logging for ASP.NET MVC 4: log4net

Logging is always an important part of a software project, tracing errors, passing audits, and allow monitoring etc.

I know how to use log4j in Spring framework, but today I have worked a little on C# MVC 4.

How to easily add logging into ASP.NET MVC 4 code base ?

I use log4net, and you can simply download it from VS NuGet store.

Steps for setting up after installation of log4net package:

1. Open  Global.asax.cs

protected void Application_Start() {
log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));

2. Open Startup.cs

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

3. Open Web.config

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="app-log.txt" />
<appendToFile value="true"/>
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %logger (line:%line) - %message%newline" />
<level value="DEBUG"/>
<appender-ref ref="RollingFileAppender" />

4. Any namespace, say in Controller:

using log4net;
public class AccountController : Controller
readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public AccountController()
private bool try(){ log.Error("Error message"); }

The only thing missing here is that I have not tried to log Database SQL error. May update this later.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s