More

    .Net Core Project 從零開始 — NLog

    Why use log?

    在開發程式上,運作時很有可能會有一些莫名的錯誤或是功能異常,這些Log能協助你快速查詢確認問題點,確認問題點在哪之後對症下藥解決問題。

    NLog官網:Link

    STEP 1 : Create ASP.NET Core project

    STEP 2 : Add dependency in csproj

    使用.NET CLI

    dotnet add package NLog --version 4.6.8dotnet add package NLog.Web.AspNetCore --version 4.9.0

    STEP 3 : Create a nlog.config file.

    放在Asp .net core專案的root 資料夾上;以下是 nlog.config file example

    <?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"
          autoReload="true"
          internalLogLevel="Info"
          internalLogFile="c:\temp\internal-nlog.txt">
    
      <!-- enable asp.net core layout renderers -->
      <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
      </extensions>
    
      <!-- the targets to write to -->
      <targets>
        <!-- write logs to file  -->
        <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
    
        <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
        <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
      </targets>
    
      <!-- rules to map from logger name to target -->
      <rules>
        <!--All logs, including from Microsoft-->
        <logger name="*" minlevel="Trace" writeTo="allfile" />
    
        <!--Skip non-critical Microsoft logs and so log only own logs-->
        <logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->
        <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
      </rules>
    </nlog>

    STEP 4 : Enable copy to bin folder

    STEP 5 : program.cs, Set up NLog for Dependency injection

    STEP 6 : Configure appsettings.json

    {
    "Logging": {
    "LogLevel": {
    "Default": "Trace",
    "Microsoft": "Information"
    }
    }
    }

    STEP 7 : 接著就可以在程式上寫一點Log method 寫至 Log file了

    由於在第5.的步驟已經進行過Nlog 的 Dependency injection ,可以直接在HomeController 的 constructor 取得到logger Service 使用它的方法

    STEP 8 : Run Web Site

    在 nlog.config file裡 範例將檔案寫至 temp folder底下

    在nlog-won裡可以看到我們所寫的Log Message

    nlog-all 就紀錄了整個站台運作的狀況

    Conclusion:這篇算是基礎篇,先入門了解Nlog設定與了解怎麼使用寫Log,之後會分享更多像是增加寫入位置至資料庫或是在什麼時機寫入Log更好

    下一篇 .Net Core Project 從零開始 — Use NLog wite log to database table.

    .Net Core Project GitHub:Link

    Source : .Net Core Project 從零開始 — NLog

    Recent Articles

    spot_img

    Related Stories

    Stay on op - Ge the daily news in your inbox