ASP.NET Core 3 NLog配置

使用NLog记录日志

手动或使用NuGet在csproj中添加依赖项

  • 安装最新版本:
  • NLog.Web.AspNetCore 4.9+
  • 如有可能,更新NLog软件包

创建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">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!--写入文件-->
    <target
     xsi:type="File"
     name="DebugFile"
     fileName="Logs\Debug\${shortdate}.log"
     layout="日志时间:${longdate}${newline}日志来源:${callsite}${newline}日志级别:${uppercase:${level}}${newline}消息内容:${message}${newline}----------------------------------------------------------------${newline}" >
    </target>
    <target
      xsi:type="File"
      name="InfoFile"
      fileName="Logs\Info\${shortdate}.log"
      layout="日志时间:${longdate}${newline}日志来源:${callsite}${newline}日志级别:${uppercase:${level}}${newline}消息内容:${message}${newline}----------------------------------------------------------------${newline}" >
    </target>
    <target
      xsi:type="File"
      name="ErrorFile"
      fileName="Logs\Error\${shortdate}.log"
      layout="日志时间:${longdate}${newline}日志来源:${callsite}${newline}日志级别:${uppercase:${level}}${newline}消息内容:${message}${newline}异常信息:${exception:format=tostring}${newline}----------------------------------------------------------------${newline}" >
    </target>
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <logger name="*" minlevel="Debug" maxLevel="Debug" writeTo="DebugFile" />
    <logger name="*" minlevel="Info" maxLevel="Info" writeTo="InfoFile" />
    <logger name="*" minlevel="Error" maxLevel="Error" writeTo="ErrorFile" />
  </rules>
</nlog>

注意:日志生成的文件在bin目录下

配置文件的更多详细信息在这里

请注意,如果删除所有其他LoggingProviders(如控制台)并且仅使用NLog,则可能必须特别注意Hosting Lifetime Startup Messages。因为这可能导致托管环境(Visual Studio / Docker / Azure容器)看不到启动的应用程序。

启用复制到bin文件夹

  • .csproj手动编辑文件并添加:
    <ItemGroup>
        <Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
    </ItemGroup>
    

修改 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

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

切记还要更新任何特定于环境的配置,以免引起任何意外。

写日志

using Microsoft.Extensions.Logging;

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

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation("这是Info等级的信息");
        return View();
    }
}

输出

日志时间:2020-08-20 16:56:24.3082
日志来源:QS.Core.Web.Areas.Admin.Controllers.HomeController.Index
日志级别:INFO
消息内容:这是Info等级的信息

----------------------------------------------------------------

如果无法输出日志文件请检查appsettings.json文件或在bin目录下查看

使用nlog.config配置NLog

官方文档

posted @ 2020-08-27 09:31  青杉  阅读(490)  评论(5编辑  收藏  举报