.NET Core使用Nlog记录日志

Posted dotNET跨平台

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.NET Core使用Nlog记录日志相关的知识,希望对你有一定的参考价值。

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中:

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

创建一个nlog.config文件。

在项目的根目录中创建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"
      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>

启用复制到bin文件夹

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

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

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

更新program.cs

更新program.cs

using System;
using NLog.Web;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;


public static void Main(string[] args)
{
    var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    try
    {
        logger.Debug("init main");
        CreateHostBuilder(args).Build().Run();
    }
    catch (Exception exception)
    {
        //NLog: catch setup errors
        logger.Error(exception, "Stopped program because of exception");
        throw;
    }
    finally
    {
        // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
        NLog.LogManager.Shutdown();
    }
}


public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
      .ConfigureWebHostDefaults(webBuilder =>
      {
          webBuilder.UseStartup<Startup>();
      })
      .ConfigureLogging(logging =>
      {
          logging.ClearProviders();
          logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
      })
      .UseNLog();  // NLog: Setup NLog for Dependency injection

配置appsettings.json

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

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

写日志

将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网站时,我们得到两个文件:

nlog-own-2019-10-14.log
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
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
2019-10-14 23:15:11.3867|0|INFO|ASP.NET_Core_3___VS2019.Controllers.HomeController|Hello, this is the index! |url: htt
nlog-all-2019-10-14.log
2019-10-14 23:15:09.3898|0|DEBUG|ASP.NET_Core_3___VS2019.Program|init main 
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. 
2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Application started. Press Ctrl+C to shut down. 
2019-10-14 23:15:11.2680|0|INFO|Microsoft.Hosting.Lifetime|Hosting environment: Development 
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 
2019-10-14 23:15:11.3238|1|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request starting HTTP/2.0 GET https://localhost:44318/   
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)' 
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). 
2019-10-14 23:15:11.3867|1|DEBUG|ASP.NET_Core_3___VS2019.Controllers.HomeController|NLog injected into HomeController 
2019-10-14 23:15:11.3867|0|INFO|ASP.NET_Core_3___VS2019.Controllers.HomeController|Hello, this is the index! 
2019-10-14 23:15:11.4161|1|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor|Executing ViewResult, running view Index. 
2019-10-14 23:15:11.5831|4|INFO|Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor|Executed ViewResult - view Index executed in 167.626ms. 
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 
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)' 
2019-10-14 23:15:11.5910|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 267.9366ms 200 text/html; charset=utf-8 
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   
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   
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   
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   
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   
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' 
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' 
2019-10-14 23:15:11.6627|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 28.7787ms 200 application/javascript 
2019-10-14 23:15:11.6696|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 52.4825ms 200 text/css 
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' 
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' 
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' 
2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 50.937400000000004ms 200 application/javascript 
2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 70.65100000000001ms 200 text/css 
2019-10-14 23:15:11.6853|2|INFO|Microsoft.AspNetCore.Hosting.Diagnostics|Request finished in 71.51610000000001ms 200 application/javascript

以上是关于.NET Core使用Nlog记录日志的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET Core使用NLog记录日志

.NET Core平台日志记录框架:NLog+Mysql

Net Core 2.1 日志记录框架NLog+Mysql配置

ASP.NET Core 使用NLog打印html格式日志

.net core 杂记:日记记录

使用NLog记录文本日志