欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.NET Core使用Nlog记录日志

程序员文章站 2024-01-29 17:51:58
...

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(全部小写)文件。

我们使用以下示例:

.NET Core使用Nlog记录日志

 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>

.NET Core使用Nlog记录日志

 

 

启用复制到bin文件夹

为nlog.config启用复制到bin文件夹

 

.NET Core使用Nlog记录日志

 

 

 

.csproj手动编辑文件并添加:

 

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

 

 

 

更新program.cs

更新program.cs

.NET Core使用Nlog记录日志

 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

.NET Core使用Nlog记录日志

 

 

 

配置appsettings.json

中指定的日志记录配置appsettings.json会覆盖对的任何调用SetMinimumLevel。因此"Default":,请根据您的需要删除或正确调整它。

.NET Core使用Nlog记录日志

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

.NET Core使用Nlog记录日志

 

 

 

 

写日志

将ILogger注入您的控制器中:

.NET Core使用Nlog记录日志

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();
    }

.NET Core使用Nlog记录日志

 

 

 

输出示例

启动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

 

.NET Core使用Nlog记录日志

 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 

.NET Core使用Nlog记录日志