开发手册 欢迎您!
软件开发者资料库

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

本文主要介绍.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文件中手动添加依赖项

  
    
    
    
  

3、创建NLog.config文件

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

                            

4、项目使用的代码 

1)创建MyClass类

 public class MyClass
 {
     private readonly ILogger _logger;
     public MyClass(ILogger 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()
        .BuildServiceProvider();
}
3)控制台项目Main方法的代码
static void Main(string[] args){ var servicesProvider = BuildDi(); var obj = servicesProvider.GetRequiredService(); 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.wonhero.com/download/5c3c9191dc72d915fc31068c