本文主要介绍ASP.NET Core 3.0中,安装配置记录日志的框架NLog的方法,以及使用NLog的记录日志的示例代码。

1、安装引用NLog相关依赖

1)使用Nuget界面管理器

搜索"NLog.Web.AspNetCore",在列表中找到它,点击"安装",然后在搜索"NLog",点击"安装"

相关文档VS(Visual Studio)中Nuget的使用

2)使用Package Manager命令安装

PM> Install-Package NLog.Web.AspNetCore
PM> Install-Package NLog

3)使用.NET CLI命令安装

> dotnet add TodoApi.csproj package NLog.Web.AspNetCore
> dotnet add TodoApi.csproj package NLog

4) 修改csproj文件

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

2、创建nlog.config配置文件

在项目根目录创建nlog.config配置文件,内容如下:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  autoReload="true"
      >
  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <targets>
    <!--屏幕打印消息-->
    <target name="console" xsi:type="ColoredConsole"
                    layout="${date:format=HH\:mm\:ss} | ${callsite} > ${message}"/>

    <!--VS输出窗口-->
    <target name="debugger" xsi:type="Debugger"
                    layout="${date:format=HH\:mm\:ss} | ${level:padding=-5} |${callsite} | ${message}" />

    <!--保存至文件-->
    <target name="error_file" xsi:type="File" archiveAboveSize="2000000" maxArchiveFiles="30"
                    fileName="${basedir}/Logs/Error/${shortdate}/error.txt"
                    layout="${longdate} | ${level:uppercase=false:padding=-5} | ${callsite} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
    <!--保存至文件-->
    <target name="info_file" xsi:type="File" archiveAboveSize="2000000" maxArchiveFiles="30"
                    fileName="${basedir}/Logs/Info/${shortdate}/info.txt"
                    layout="${longdate} | ${level:uppercase=false:padding=-5} | ${callsite} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
  </targets>
  <rules>
    <!--<logger name="*" writeTo="console" />-->
    <logger name="*" minlevel="Debug" writeTo="debugger" />
    <logger name="*" minlevel="Error" writeTo="error_file" />
    <logger name="*" minlevel="Info" writeTo="info_file" />
  </rules>
</nlog>

或者

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

相关文档https://github.com/NLog/NLog/wiki/Configuration-file

3、设置nlog.config拷贝到bin

配置nlog.config启用copy to bin文件夹:

httpsfileaionlifexyzsourcedownloadid5ead885bdc72d90263e632d0

或者修改.csproj文件添加下面内容:

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

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

5、配置 appsettings.json

appsettings中指定的日志配置。json覆盖了对SetMinimumLevel的所有调用。因此,要么删除"Default":要么根据需要对其进行正确调整。

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

还请记住更新任何特定于环境的配置,以避免任何意外,例如:

appsettings.Development.json

6、Write记录日志

在controller中注入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();
}

相关文档:

.NET Core nlog使用SQLite记录Log日志配置及示例代码

.NET Core和ASP.NET Core 日志框架nlog安装配置及示例代码 

.NET Core 2.0 Console(控制台)项目 Microsoft.Extensions.Logging nlog配置使用

.Net nlog配置文件中配置项说明文档

https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3

推荐文档

相关文档

大家感兴趣的内容

随机列表