NLog在.Net Core控制台应用程序上的使用

NLog在.Net Core控制台应用程序上的使用

  • Nuget包的引用
  • 创建nlog.config配置文件
  • 创建两个runner 类
  • 在Program创建依赖注入(DI)容器和修改main()的代码
  • 运行程序后

Nuget包的引用

NLog.Extensions.Logging
Microsoft.Extensions.DependencyInjection

创建nlog.config配置文件






  
  
    
    
    


  

  
  
    

  

创建两个runner 类

第一个 Runner类

using Microsoft.Extensions.Logging;

namespace NLogInDotnetCoreConlose
{
    public class Runner
    {
        private readonly ILogger _logger;

        public Runner(ILogger logger)
        {
            _logger = logger;
        }

        public void DoAction(string name)
        {
            _logger.LogDebug(20, "Doing hard work! {Action}", name);
        }


    }
}

第二个Runner类

using Microsoft.Extensions.Logging;

namespace NLogInDotnetCoreConlose
{
    public class Runner2 
    {
        private readonly ILogger _logger;

        public Runner2(ILogger logger)
        {
            _logger = logger;
        }

        public void DoAction(string name)
        {
            _logger.LogDebug(20, "Doing hard work! {Action}", name);
        }
    }
}

在Program创建依赖注入(DI)容器和修改main()的代码

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

namespace NLogInDotnetCoreConlose
{
    class Program
    {
        static void Main(string[] args)
        {
            var logger = LogManager.GetLogger("*");
            logger.Info("这个信息");
            logger.Debug("这个调试");
            logger.Error("这个是错误");
            var servicesProvider = BuildDi();
            var runner = servicesProvider.GetRequiredService();
            runner.DoAction("runner Action");

            var runner2 = servicesProvider.GetRequiredService();
            runner.DoAction("runner2 Action");

            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)
            LogManager.Shutdown();
        }

        private static ServiceProvider BuildDi()
        {            

            return new ServiceCollection()
                .AddLogging(builder => {
                    builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                    builder.AddNLog(new NLogProviderOptions
                    {
                        CaptureMessageTemplates = true,
                        CaptureMessageProperties = true
                    });
                })
                .AddTransient()
                .AddTransient()
                .BuildServiceProvider();
        }
    }
}

运行程序后

窗口会显示如下图内容
NLog在.Net Core控制台应用程序上的使用_第1张图片
同时logs目录下也会生成同样内容的日志文档

你可能感兴趣的:(.Net,Core)