1. 程式人生 > >在.net core web 專案中使用Nlog記錄日誌

在.net core web 專案中使用Nlog記錄日誌

第1步,新增NLog.Web.AspNetCore包引用

方法1

在專案上右擊“依賴項”---“管理Nuget程式包(N)…”,然後在瀏覽對話方塊中輸入“NLog.Web.AspNetCore”查詢包,找到後選中並單擊“安裝”。

 

 

方法2

或者直接在包管理器控制檯輸入以下命令:

Install-Package NLog.Web.AspNetCore

 

 

  

第2步,新增Nlog.config配置檔案

(1)在專案名稱上擊右鍵,選擇 ”新增” --- “新建項”。

 

 

(2)在彈出的“新增新項”對話方塊中左邊選擇“ASP.NET Core”,右邊選擇“XML檔案” ,“名稱”框中輸入“Nlog.config”,最後單擊“新增”按鈕。

 

 

(3)修改剛新增的Nlog.config檔案內容如下:

配置檔案內容:

<?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">

    <targets>

        <target xsi:type="File"

                name="logfile"

                fileName="${basedir}/logs/${shortdate}.log"

                keepFileOpen="false"

                layout="${longdate}|${callsite:fileName=True}

                |${uppercase:${level}}|${message} ${exception}" />

        <target xsi:type="File"

                name="debugfile"

                fileName="${basedir}/logs/${shortdate}_debug.log"

                keepFileOpen="false"

                layout="${longdate}|${callsite:fileName=True}

                |${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="File"

            name="errfile"

            fileName="${basedir}/logs/${shortdate}_error.log"

            keepFileOpen="false"

            layout="${longdate}|${callsite:fileName=True}

            |${uppercase:${level}}|${message} ${exception}" />

  </targets>

    <rules>

    <logger name="*" level="Debug" writeTo="debugfile" />

      <logger name="*" level="Error" writeTo="errfile" />

    <logger name="*" minlevel="Trace" writeTo="logfile" />

    </rules>

</nlog>

 

(4)修改Nlog.config檔案屬性“複製到輸出目錄”為“始終複製”(這一步很重要,否則執行時會報找不到檔案的異常).

 

 

 

 

第3步,在專案中開啟Startup.cs檔案,修改Configure方法

(1)   先給Configure方法增加IloggerFactory loggerFactory引數注入日誌物件,此時增加的程式碼會報錯,需在類檔案頭部新增引用程式碼:

using Microsoft.Extensions.Logging;

 

 

(2)   接著在Configure方法內部增加如下兩行程式碼:

loggerFactory.AddNLog();//使用NLog作為日誌記錄工具  

env.ConfigureNLog("Nlog.config");  //引入Nlog配置檔案

注意:配置檔名為 ”Nlog.config” ,則env.ConfigureNLog("Nlog.config")這行程式碼可以不需要(Nlog預設找的就是Nlog.config檔案)。如果是其他名字,則必須加上這一行程式碼。

新增以上程式碼後會報錯,需在類檔案頭部新增如下引用程式碼:

using NLog.Extensions.Logging;

using NLog.Web;

 

 

第4步,在建構函式中注入日誌物件(以Home控制器為例)。

ILogger<HomeController> logger;

public HomeController(ILogger<HomeController> _logger)

{

    logger = _logger;

}

增加程式碼後程序會報錯,需在類檔案頭部增加如下引用程式碼:

using Microsoft.Extensions.Logging;

 

程式碼如下圖所示:

 

 

第5步:在控制器的Index方法中增加寫日誌的測試方法。

增加的程式碼如下:

public IActionResult Index()

{

    logger.LogInformation("Index Begin...");

    logger.LogTrace("Index Begin...");

    logger.LogDebug("Index Begin...");

    logger.LogError("Index Begin...");

 

    return View();

}

 

如下圖所示:

 

 

第6步:執行程式測試日誌記錄是否成功。

執行專案後,開啟根目錄下的:bin\Debug\netcoreapp2.2\logs

子目錄,即可以看到生成的日誌檔案