Blog

Filter posts by Category Or Tag of the Blog section!

Using Log4net in asp.net MVC

Tuesday, 26 February 2013

Log4net is one the famous open source library for logging between asp.net developers. I recommend you that if you don't want anything else but logging in your asp.net MVC project, use an open source project for logging like Log4net. Get the latest version of the project from Nuget . The following class is:

 

 

  public interface ILogger

    {

        void Log(string message);

        void Info(string message);

        void Error(string message);

        void Error(string message, Exception exception);

    }

 

 

  public class Log4NetAdapter : ILogger

    {

        private readonly ILog _log;

 

        public Log4NetAdapter()

        {

            _log = LogManager.GetLogger(this.GetType());

            XmlConfigurator.Configure();

         }

 

        public void Log(string message)

        {

            _log.Info(message);

        }

 

        public void Info(string message)

        {

            _log.Info(message);

        }

 

        public void Error(string message)

        {

            _log.Error(message);

        }

 

        public void Error(string message, Exception exception)

        {

            _log.Error(message, exception);

        }

    }

 

Note that you have to inject the above interface to the class via a DI container. Rather than above you have to add some configurations to your web.config:

 

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

 

And the log4net section itself:

 

<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="100KB" />
      <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>

 

 as you can see in the configuration, logs will be stored in a file named log.txt inside App_Data.

comments powered by Disqus