NLog .net core

初探.net core NLog

林郁昇 Sean Lin 2019/09/14 17:47:22
4614

NLog

前言

NLog是一個基於.NET平臺編寫的類庫,我們可以使用NLog在應用程式中新增極為完善的跟蹤除錯程式碼。NLog是一個簡單靈活的.NET日誌記錄類庫。

ASP.Net Core MVC專案中使用NLog
需先安裝以下套件:

 

 

安裝完後專案內會多出NLog.Config需要把2838行註解打開(targetrules)

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <!-- optional, add some variables
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
  <variable name="myvar" value="myvalue"/>

  <!--
  See https://github.com/nlog/nlog/wiki/Configuration-file
  for information on customizing logging rules and outputs.
   -->
  <targets>

    <!--
    add your targets here
    See https://github.com/nlog/NLog/wiki/Targets for possible targets.
    See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
    -->

    <!--
    Write events to a file with the date in the filename.
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    -->
  </targets>

  <rules>
    <!-- add your logging rules here -->

    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->
  </rules>
</nlog>

 

 

接著在Program.cs 加入第5行及12~17

public class Program
    {
        public static void Main(string[] args)
        {
            NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
             .ConfigureLogging(logging =>
             {
                 logging.ClearProviders();
                 logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
             })
        .UseNLog();  // NLog: setup NLog for Dependency injection
    }

 

 

都設定完之後可以開始進行測試了,在Controller 注入ILogger

public class HomeController : Controller
{
        private readonly ILogger logger;

        public HomeController(ILogger<HomeController> _logger)
        {
            this.logger = _logger;
        }

        public IActionResult Index()
        {
            
            logger.LogDebug("This is debug log");           
            
            return View();
        }
}

 

可依照log等級寫入訊息

 

執行網站後,在專案資料夾可找到log檔

 

以上範例是只寫入單一log檔,我想區分log檔能嗎? 

 

NLog 設定寫入不同資料夾

 

rules裡可設定多個logger用來指定相對應的target,target再設定不同的路徑即可。

 <!--
    Write events to a file with the date in the filename.-->
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    <target xsi:type="File" name="debug" fileName="${basedir}/logs/debug/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    <target xsi:type="File" name="warning" fileName="${basedir}/logs/warning/${shortdate}.log"
        layout="${longdate} ${uppercase:${level}} ${message}" />


  </targets>

  <rules>
    <!-- add your logging rules here -->

    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"-->
    <logger name="*" minlevel="Debug" writeTo="f" />
    <logger name="debug" minlevel="Debug" writeTo="debug"/>
    <logger name="warning" minlevel="Debug" writeTo="warning"/>

  </rules>

 

Controller裡,用LogManager取得對應的logger名稱,再寫入log

public class HomeController : Controller
{
        private Logger debugerlog = LogManager.GetLogger("debug");
        private Logger warninglog = LogManager.GetLogger("warning");
        public IActionResult Index()
        {

            debugerlog.Debug("This is debug log");
            warninglog.Warn("This is warning log");
            return View();
        }
}

 

log資料夾內發現有區分資料夾了

 

小結

此篇紀錄一下簡單的使用方式,還有更多的東西可以玩,可能未來專案套用,再進行更深入的探討。

 

參考資料

https://github.com/NLog/NLog

 

 

林郁昇 Sean Lin