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

1、.NET Core 2.0项目中安装引用NLog相关依赖

1)使用Nuget界面管理器

搜索"NLog.Extensions.Logging",在列表中找到它,点击"安装",在分别搜索"NLog""Microsoft.Extensions.DependencyInjection"“Microsoft.Extensions.Configuration.Json”,然后在点击"安装"

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

2)使用Package Manager命令安装

PM> Install-Package NLog.Extensions.Logging
PM> Install-Package NLog
PM> Install-Package Microsoft.Extensions.DependencyInjection
PM> Install-Package Microsoft.Extensions.Configuration.Json

3)使用.NET CLI命令安装

> dotnet add TodoApi.csproj package NLog.Extensions.Logging
> dotnet add TodoApi.csproj package NLog
> dotnet add TodoApi.csproj package Microsoft.Extensions.DependencyInjection
> dotnet add TodoApi.csproj package Microsoft.Extensions.Configuration.Json

4) 修改csproj文件

<ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.0" />
    <PackageReference Include="NLog" Version="4.6.5" />
    <PackageReference Include="NLog.Extensions.Logging" Version="1.5.1" />
</ItemGroup>

2、创建nlog.config配置文件

在应用程序项目的根目录中创建nlog.config(全部小写)文件(文件属性:始终复制):

 nlog copy to bin

在项目根目录创建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、修改.NET Core 2.0项目代码

1) 创建runner class

 public class Runner
{
private readonly ILogger<Runner> _logger;
public Runner(ILogger<Runner> logger)
{
_logger = logger;
}
public void DoAction(string name)
{
_logger.LogDebug(20, "Doing hard work! {Action}", name);
}
}

2) 配置依赖注入(DI:Dependency injector)container

private static IServiceProvider BuildDi(IConfiguration config)
{
   return new ServiceCollection()
      .AddTransient<Runner>() // Runner is the custom class
      .AddLogging(loggingBuilder =>
      {
            // configure Logging with NLog
            loggingBuilder.ClearProviders();
            loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            loggingBuilder.AddNLog(config);
      })
      .BuildServiceProvider();
}

3) 引用所需的命名空间

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;

4) 修改main()方法

创建DI container,获取到Runner实例并运行:

static void Main(string[] args)
{
   var logger = LogManager.GetCurrentClassLogger();
   try
   {
      var config = new ConfigurationBuilder()
         .SetBasePath(System.IO.Directory.GetCurrentDirectory()) //From NuGet Package Microsoft.Extensions.Configuration.Json
         .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
         .Build();
      var servicesProvider = BuildDi(config);
      using (servicesProvider as IDisposable)
      {
         var runner = servicesProvider.GetRequiredService<Runner>();
         runner.DoAction("Action1");
         Console.WriteLine("Press ANY key to exit");
         Console.ReadKey();
      }
   }
   catch (Exception ex)
   {
      // NLog: catch any exception and log it.
      logger.Error(ex, "Stopped program because of exception");
      throw;
   }
   finally
   {
      // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
      LogManager.Shutdown();
   }
}

相关文档:

Getting-started-with-.NET-Core-2---Console-application

ASP.NET Core 3.0安装配置使用NLog的方法及示例代码

.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

推荐文档

相关文档

大家感兴趣的内容

随机列表