Tuesday, February 14, 2017

How to use log4net in a ASP.NET Web Application

Add the following configurations in the web.config file.

<?xml version="1.0"?>
<configuration>

  <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" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>    

    <root>
      <level value="ALL" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
  </log4net>

</configuration>
logs folders is created on the root directory path of the web application. Inside the folder log.txt file is created.
Log records are appended to the same log.txt file.
When the file size reaches 10MB it'll be renamed to log.txt.1 and it''l continue till log.txt.9.

Sample log records.

2017-02-06 13:36:41,798 [26] INFO WarehouseAPI.TaskService [(null)] - Starting task.
2017-02-06 13:36:41,878 [26] INFO WarehouseAPI.TaskService [(null)] - Completing task.

Example usage.

public class TaskService 
{
    private static readonly log4net.ILog logger =  LogManager.GetLogger(typeof(TaskService));

    public HealthTestResultClient TestHealth()
    {
        logger.Info("Testing API health.");

        return new HealthTestResultClient() { Message = msg , Success = res };
    }
}

No comments:
Write comments
Recommended Posts × +