.Net Core Project 從零開始 — NLog

    This Content Is Only For Subscribers

    Please subscribe to unlock this content. Enter your email to get access.
    Your email address is 100% safe from spam!

    Why use log?



    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=""
      <!-- enable core layout renderers -->
        <add assembly="NLog.Web.AspNetCore"/>
      <!-- the targets to write to -->
        <!-- 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}" />
      <!-- rules to map from logger name to target -->
        <!--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" />

    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 就紀錄了整個站台運作的狀況


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

    .Net Core Project GitHub:Link

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

    Recent Articles


    Related Stories

    Stay on op - Ge the daily news in your inbox