本文主要介绍.NET Core(仅限VS2017)控制台项目,使用Microsoft.Extensions.Logging和NLog配置使用。

1、创建一个.NET Core控制台项目

在Visual Studio 2017中,使用.NET 4.6.1+或.NET Core 2

httpsfileaionlifexyzsourcedownloadid5c3c8efbdc72d915fc31068b

2、手动在csproj文件中添加依赖或使用Nuget安装

1)使用Nuget安装

项目上右键=》点击 "管理NuGet程序包" =》分别搜索 "NLog.Extensions.Logging" 和 "Microsoft.Extensions.DependencyInjection" =》点击 "安装"

2)在csproj文件中手动添加依赖项

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="1.1.0" />
    <PackageReference Include="NLog" Version="4.5.0" />
    <PackageReference Include="NLog.Extensions.Logging" Version="1.0.0" />
  </ItemGroup>

3、创建NLog.config文件

在项目根目录创建NLog.config文件

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogFile="c:\temp\console-example-internal.log"
      internalLogLevel="Info" >

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file -->
    <target xsi:type="File" name="target1" fileName="c:\temp\console-example.log"
            layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
    <target xsi:type="Console" name="target2"
            layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
  </targets>
  <!-- rules to map from logger name to target -->
  <rules>
    <logger name="*" minlevel="Trace" writeTo="target1,target2" />
  </rules>
</nlog>

4、项目使用的代码 

1)创建MyClass类

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

 }

2)设置依赖注入(DI)容器

private static ServiceProvider BuildDi()
{
    return new ServiceCollection()
        .AddLogging(builder => {
            builder.SetMinimumLevel(LogLevel.Trace);
            builder.AddNLog(new NLogProviderOptions {
                CaptureMessageTemplates = true,
                CaptureMessageProperties = true
            });
        })
        .AddTransient<MyClass>()
        .BuildServiceProvider();
}
3)控制台项目Main方法的代码
static void Main(string[] args) { var servicesProvider = BuildDi(); var obj = servicesProvider.GetRequiredService<MyClass>(); obj.DoAction("Action1"); Console.WriteLine("Press ANY key to exit"); Console.ReadLine(); // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); }

5、项目代码下载

下载地址:https://www.cjavapy.com/download/5c3c9191dc72d915fc31068c

推荐文档