NLog.Extensions.Logging 使用 (3)

发布时间 2023-12-21 09:04:08作者: 落花流水1173

GitHub链接

NLog.Extensions.Logging makes it possible to use NLog with Microsoft ILogger abstraction and dependency injection.

NLog.Extensions.Logging主要是为了把NLog通过依赖注入注册到容器中,使用者通过构造器注入获取ILogger<T>

上一篇文章讲的NLog没有结合依赖注入

1、安装Nuget包:NLog.Extensions.Logging

2、添加配置文档nlog.config,并设置该文档属性“较新则复制”

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

    <targets>
        <target name="logfile" xsi:type="File" fileName="file.txt" />
        <target name="logconsole" xsi:type="Console" />
    </targets>

    <rules>
        <logger name="*" minlevel="Info" writeTo="logconsole" />
        <logger name="*" minlevel="Debug" writeTo="logfile" />
    </rules>
</nlog>

3、创建Test类,通过构造函数注入ILogger<Test>

 public class Test
 {
    private readonly ILogger<Test> logger;

     public Test(ILogger<Test> logger)//通过DI注入
     {
         this.logger = logger;
     }

     public void Run()
     {
         logger.LogDebug("准备登录");
         logger.LogWarning("校验失败");
         logger.LogWarning("再次校验失败");
         logger.LogError("多次登录失败");

         try
         {
             string str = null;
             str.Substring(0, 2);
         }
         catch (Exception ex)
         {
             logger.LogCritical(ex, "critical");//可以输出异常信息
         }
     }
 }

4、Main函数

  static void Main(string[] args)
  {
    ServiceCollection services = new ServiceCollection();
      services.AddLogging(loggingbuilder=> loggingbuilder.AddNLog());//配置NLogProvider到Logging中并注册到容器
      services.AddScoped<Test>();
      using (var scope = services.BuildServiceProvider())
      {
        var test=  scope.GetRequiredService<Test>();
          test.Run();
      }
  }

运行结果:

 运行目录下生成file日志文件