Tuesday, January 16, 2018

ASP.NET Core 2.0 - Logging with Log4Net (Microsoft.Extensions.Logging.Log4Net.AspNetCore)


Below are steps in integrating Log4Net in Asp.Net Core.

1) First install required package:
    dotnet add package Microsoft.Extensions.Logging.Log4Net.AspNetCore
2) Create file log4net.config with following xml content

    <?xml version="1.0" encoding="utf-8" ?>
    <log4net>
      <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <file type="log4net.Util.PatternString" value="Logs/Logs_%date{yyyyMMdd}.txt" />
        <rollingStyle value="Date" />
        <appendToFile value="true" />
        <rollingStyle value="Size" />
        <datePattern value="yyyyMMdd" />
        <maxSizeRollBackups value="10" />
        <maximumFileSize value="10000KB" />
        <staticLogFileName value="true" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%-5level %date{dd-mm-yyyy HH:mm:ss} %logger [%thread] - %message %exception%newline" />
        </layout>
      </appender>
      <root>
        <appender-ref ref="RollingFileAppender" />
        <level value="All" />
      </root>
    </log4net>
3) Inside Appsetting.js add section to save log4net config path ,section is added on same level as "Logging"

  "Log4NetConfigFile": {
    "Name": "Services/LoggingService/log4net.config"
  }

    My log4net.config is inside services/LoggingService you can add it in project root if so section will need tiny modification in path as below.

    "Log4NetConfigFile": {
        "Name": "log4net.config"
      }
     

3) inside Configure method in StartUp.cs add

        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddLog4Net(Configuration.GetValue<string>("Log4NetConfigFile:Name"));

4) Inside Your Test controller add class variable
    private readonly ILogger Logger;

   and inject its dependency through constructor

public TestController(ILoggerFactory DepLoggerFactory, IHostingEnvironment DepHostingEnvironment)
        {
            HostingEnvironment = DepHostingEnvironment;
            Logger = DepLoggerFactory.CreateLogger("Controllers.TestController");
        }

5) Now Create Test Action


     public IActionResult  GetAllMyModels(string id)
        {
            var comments = (from m in Db.MyModelChild
                            where m.ParentId.ToString() == id
                            select m).ToList();

            Logger.LogInformation("Test log information 001");
            if (comments.Count() == 0)
            {
                Logger.LogInformation("Test log information 002");
                return NotFound();
            }
            return new ObjectResult(comments);
        }

      on success this method emit MyModelChild objects as json

6) Now check to Logs folder in root redirectory its created with pattern of YYYYMMDD prepended with "Logs_"
    Logs_20180116.txt.Logged text also include timestamp.
   
    Output:
        INFO  16-13-2018 11:13:24 Controllers.TestController [7] - Test log information 001

        In my case i am getting data so above log text will be there along with other output from dotnet run which falls in info.
   
     we can write other kind of log than warning too.

No comments:

Post a Comment