Log4net logging in asp.net MVC

Make changes in web.config file as follows

<configuration>
  <configSections>    
    ...
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <appSettings>
	...
	<add key="log4net.Config" value="log4net.config"/>
    <add key="log4net.Config.Watch" value="True"/>
  </appSettings>
  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="D:/Logs/TTG SmartANPR REST Service/smartanprrest_%date{ddMMyyyy}.log" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />      
      <datePattern value="yyyyMMdd" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="RollingFileAppender"/>
    </root>
  </log4net>
</configuration>

Add following lines in WebApiConfig.cs

config.EnableSystemDiagnosticsTracing();
log4net.Config.XmlConfigurator.Configure();

Add Logging class

public static class Logger
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static log4net.ILog Log
        {
            get { return log; }
        }
    }

To Log write below line

Logger.Log.Debug("TEST");

Leave a Reply

Your email address will not be published.