Beginner’s Guide to Using Log4NET in an ASP.NET MVC Application

Logging is an integral part of any application. There are many options and not all of them good. Log4NET is a great framework for both simple and extremely complex scenarios, allowing you to choose the log format, the storage medium, and custom rules for messages and levels. Creating new message handlers is an easy process and Log4NET can be configured quite easily via config files, allowing you to change the configuration without requiring a recompile and deploy.

 

NuGet

Start by adding a reference to Log4NET in NuGet.

Global.asax.cs

In the Application_Start method in the Global.asax.cs file, we need to call the Configure method. The Configure method has 10 different overloads but we are only interested in the default. Some of the more useful overloads allows you to pass in a configuration file, the URL of a configuration file, and a code repository.

log4net.Config.XmlConfigurator.Configure();

Configuration

Next, we have to add the configuration to the web.config file. Everything here goes inside theĀ <configuration>...</configuration> tag.

 

<configSections>  
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />  
</configSections>  
   
<log4net debug="false">  
  <appender name="LogFileAppender" type="log4net.Appender.FileAppender">  
    <param name="File" value="C:\log\testlog.log" /> 
    <layout type="log4net.Layout.PatternLayout">  
      <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />  
    </layout>  
  </appender>  
  <root>  
  <level value="All" />  
    <appender-ref ref="LogFileAppender" />  
  </root>  
</log4net>

Usage

Finally, we can use it. You can append this in an action result in this way.

log4net.ILog logger = log4net.LogManager.GetLogger(typeof(HomeController));

logger.Error(new InvalidCastException("Division by zero"));

 

That’s all there is to it.

 

Leave a Reply

Your email address will not be published.