Introduction
Logging is a method of tracking/monitoring what is going on when an application is in progress/running. Log records will be most needed items when something goes wrong in your application, be it Windows Forms, mobile or web applications.
Here I will be walking through the basic steps in implementing logging functionality using Apache log4net framework in an ASP.NET MVC 5 application.
I am using Visual Studio Express 2013 for Web as my development environment targeting .NET framework 4.5.
Step 1
Open Visual Studio 2013 for Web and create a new ASP.NET Web application selecting MVC template.
Step 2
Here in this demo application, we are going to use Apache log4net framework for logging. We need to add reference of log4net DLL using NuGet package manager.
- In VS 2013 Solution Explorer -> Right click on Reference and Select Manage NuGet Packages.
- Search for ‘log4net’ and Install.
Once installation is successful, we can see the log4net DLL added under the Solution explorer Reference section as shown below:
Step 3
Next, we need to configure our application to use log4net logging framework. Add the below line in your startup.cs file in ASP.NET MVC5 Solution folder. The below line of code provides information about log4net configuration file.
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]
Step 4
Next, add the below section to web.config file.
<configSections>
<!---->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net debug="true">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
Step 5
Next modify Global.asax.cs and add the below code inside Application_Start()
method.
log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
Now our log4net library is ready to use with MVC5 application.
Step 6
Add logger declaration in classes for which we want to make logs as below:
readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Step 7
Use the logger.Error()
method to log messages when needed.
Run an application and we can see the log file generated under the logs folder under the application root directory as configured in the web config file.