.NET Core使用Nlog記錄日誌

ajax發表於2020-10-04

NLog是適用於各種.NET平臺(包括.NET標準)的靈活,免費的日誌記錄平臺。NLog使寫入多個目標變得容易 。(資料庫,檔案,控制檯)並即時更改日誌記錄配置。

NLog支援結構化 和傳統日誌記錄。

NLog的重點是:高效能,易於使用,易於擴充套件和靈活配置。

特徵

易於配置

通過配置檔案 和以程式設計方式,NLog都非常易於配置。即使不重新啟動應用程式,也可以更改配置。

可模板化

每個日誌訊息都可以使用各種佈局渲染進行模板化

可擴充套件的

即使NLog具有目標和預定義的佈局,您也可以編寫自定義目標或傳遞自定義值

結構化日誌

全面支援結構化日誌記錄

目標

目標用於顯示,儲存日誌訊息或將日誌訊息傳遞到另一個目標。NLog可以為每個日誌訊息動態寫入多個目標之一。

現成提供了30多個目標,其中包括:

 文件

使用自動檔案命名和歸檔功能,將日誌寫入任意數量的檔案。預設情況下,NLog不會鎖定您的檔案。

 事件記錄日誌

寫入事件日誌本地或遠端

 資料庫

將日誌儲存在.NET支援的 資料庫中

 控制檯

實時寫入命令列控制檯,包括訊息的 顏色編碼

 電子郵件

每當出現應用程式錯誤時, 您都可以傳送電子郵件

 ASP.NET核心記錄

將日誌訊息寫入ASP.NET Core日誌記錄

還有一些包裝器目標,它們提供 緩衝, 負載平衡, 故障轉移情況, 非同步寫入和更多方案。目標的完整列表在配置選項頁面上。如果找不到適合您需求的目標,則可以 輕鬆編寫自定義目標。

 

支援

NLog支援以下平臺:

  • .NET Framework 3.5、4、4.5-4.8

  • .NET Framework 4客戶端配置檔案

  • Xamarin Android

  • Xamarin iOs

  • Windows Phone 8

  • Silverlight 4和5

  • 單聲道4

  • ASP.NET 4(NLog.Web程式包)

  • ASP.NET Core(NLog.Web.AspNetCore程式包)

  • .NET Core(NLog.Extensions.Logging程式包)

  • .NET Standard 1.x-NLog 4.5

  • .NET Standard 2.x-NLog 4.5

  • UWP-NLog 4.5

     

     

    入門

建立一個新的ASP.NET Core專案

在Visual Studio 2019中。

手動或使用NuGet在csproj中新增依賴項

安裝最新版本:

  • NLog.Web.AspNetCore 4.9+

  • 如有可能,更新NLog軟體包

在csproj中:

1 <PackageReference Include="NLog.Web.AspNetCore" Version="4.9.0" />
2 <PackageReference Include="NLog" Version="4.6.7" />

 

 

建立一個nlog.config檔案。

在專案的根目錄中建立nlog.config(全部小寫)檔案。

我們使用以下示例:

複製程式碼

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4       autoReload="true"
 5       internalLogLevel="Info"
 6       internalLogFile="c:\temp\internal-nlog.txt">
 7 
 8   <!-- enable asp.net core layout renderers -->
 9   <extensions>
10     <add assembly="NLog.Web.AspNetCore"/>
11   </extensions>
12 
13   <!-- the targets to write to -->
14   <targets>
15     <!-- write logs to file  -->
16     <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
17             layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
18 
19     <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
20     <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
21             layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
22   </targets>
23 
24   <!-- rules to map from logger name to target -->
25   <rules>
26     <!--All logs, including from Microsoft-->
27     <logger name="*" minlevel="Trace" writeTo="allfile" />
28 
29     <!--Skip non-critical Microsoft logs and so log only own logs-->
30     <logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->
31     <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
32   </rules>
33 </nlog>

複製程式碼

 

 

啟用複製到bin資料夾

為nlog.config啟用複製到bin資料夾

 

 

 

 

.csproj手動編輯檔案並新增:

 

1  <ItemGroup>
2     <Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
3   </ItemGroup>

 

 

 

更新program.cs

更新program.cs

複製程式碼

 1 using System;
 2 using NLog.Web;
 3 using Microsoft.AspNetCore.Hosting;
 4 using Microsoft.Extensions.Logging;
 5 using Microsoft.Extensions.Hosting;
 6 
 7 public static void Main(string[] args)
 8 {
 9     var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
10     try
11     {
12         logger.Debug("init main");
13         CreateHostBuilder(args).Build().Run();
14     }
15     catch (Exception exception)
16     {
17         //NLog: catch setup errors
18         logger.Error(exception, "Stopped program because of exception");
19         throw;
20     }
21     finally
22     {
23         // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
24         NLog.LogManager.Shutdown();
25     }
26 }
27 
28 public static IHostBuilder CreateHostBuilder(string[] args) =>
29     Host.CreateDefaultBuilder(args)
30       .ConfigureWebHostDefaults(webBuilder =>
31       {
32           webBuilder.UseStartup<Startup>();
33       })
34       .ConfigureLogging(logging =>
35       {
36           logging.ClearProviders();
37           logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
38       })
39       .UseNLog();  // NLog: Setup NLog for Dependency injection

複製程式碼

 

 

 

配置appsettings.json

中指定的日誌記錄配置appsettings.json會覆蓋對的任何呼叫SetMinimumLevel。因此"Default":,請根據您的需要刪除或正確調整它。

複製程式碼

 1 {
 2   "Logging": {
 3     "IncludeScopes": false,
 4     "LogLevel": {
 5       "Default": "Trace",
 6       "Microsoft": "Warning",
 7       "Microsoft.Hosting.Lifetime": "Information"
 8     }
 9   },
10   "AllowedHosts": "*"
11 }

複製程式碼

 

 

 

 

寫日誌

將ILogger注入您的控制器中:

複製程式碼

using Microsoft.Extensions.Logging;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
        _logger.LogDebug(1, "NLog injected into HomeController");
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Hello, this is the index!");
        return View();
    }

複製程式碼

 

 

 

輸出示例

啟動ASP.NET Core網站時,我們得到兩個檔案:

1 nlog-own-2019-10-14.log
2 2019-10-14 23:15:09.3898|0|DEBUG|ASP.NET_Core_3___VS2019.Program|init main |url: |action: |ASP.NET_Core_3___VS2019.Program.Main
3 2019-10-14 23:15:11.3867|1|DEBUG|ASP.NET_Core_3___VS2019.Controllers.HomeController|NLog injected into HomeController |url: https://localhost/|action: Index|ASP.NET_Core_3___VS2019.Controllers.HomeController..ctor
4 2019-10-14 23:15:11.3867|0|INFO|ASP.NET_Core_3___VS2019.Controllers.HomeController|Hello, this is the index! |url: htt

 

複製程式碼

 1 nlog-all-2019-10-14.log
 2 2019-10-14 23:15:09.3898|0|DEBUG|ASP.NET_Core_3___VS2019.Program|init main 
 3 2019-10-14 23:15:10.9142|0|INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|User profile is available. Using 'C:\Users\Julian\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest. 
 4 2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Application started. Press Ctrl+C to shut down. 
 5 2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Hosting environment: Development 
 6 2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Content root path: D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019 
 7 2019-10-14 23:15:11.3238|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/   
 8 2019-10-14 23:15:11.3434|0|INFO|Microsoft.AspNetCore.Routing.EndpointMiddleware|Executing endpoint 'ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019)' 
 9 2019-10-14 23:15:11.3867|3|INFO|Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker|Route matched with {action = "Index", controller = "Home"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Index() on controller ASP.NET_Core_3___VS2019.Controllers.HomeController (ASP.NET Core 3 - VS2019). 
10 2019-10-14 23:15:11.3867|1|DEBUG|ASP.NET_Core_3___VS2019.Controllers.HomeController|NLog injected into HomeController 
11 2019-10-14 23:15:11.3867|0|INFO|ASP.NET_Core_3___VS2019.Controllers.HomeController|Hello, this is the index! 
12 2019-10-14 23:15:11.4161|1|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor|Executing ViewResult, running view Index. 
13 2019-10-14 23:15:11.5831|4|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor|Executed ViewResult - view Index executed in 167.626ms. 
14 2019-10-14 23:15:11.5831|2|INFO|Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker|Executed action ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019) in 196.6052ms 
15 2019-10-14 23:15:11.5831|1|INFO|Microsoft.AspNetCore.Routing.EndpointMiddleware|Executed endpoint 'ASP.NET_Core_3___VS2019.Controllers.HomeController.Index (ASP.NET Core 3 - VS2019)' 
16 2019-10-14 23:15:11.5910|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 267.9366ms 200 text/html; charset=utf-8 
17 2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/jquery/dist/jquery.min.js   
18 2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/css/site.css   
19 2019-10-14 23:15:11.6171|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/bootstrap/dist/css/bootstrap.min.css   
20 2019-10-14 23:15:11.6365|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/lib/bootstrap/dist/js/bootstrap.bundle.min.js   
21 2019-10-14 23:15:11.6365|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/js/site.js?v=4q1jwFhaPaZgr8WAUSrux6hAuh0XDg9kPS3xIVq36I0   
22 2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/js/site.js'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\js\site.js' 
23 2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/css/site.css'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\css\site.css' 
24 2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 28.7787ms 200 application/javascript 
25 2019-10-14 23:15:11.6696|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 52.4825ms 200 text/css 
26 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/js/bootstrap.bundle.min.js'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\lib\bootstrap\dist\js\bootstrap.bundle.min.js' 
27 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/bootstrap/dist/css/bootstrap.min.css'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\lib\bootstrap\dist\css\bootstrap.min.css' 
28 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware|Sending file. Request path: '/lib/jquery/dist/jquery.min.js'. Physical path: 'D:\nlog\NLog.Web\examples\ASP.NET Core 3\ASP.NET Core 3 - VS2019\wwwroot\lib\jquery\dist\jquery.min.js' 
29 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 50.937400000000004ms 200 application/javascript 
30 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 70.65100000000001ms 200 text/css 
31 2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 71.51610000000001ms 200 application/javascript 

複製程式碼

 

 

 

相關文章