简体   繁体   English

使用 NLog 的多个依赖注入容器时没有 output

[英]No output when using multiple dependency injection containers with NLog

I have set NLog through dependency injection, one place, where I injecting the logger is my main Class Application , in this class I have created instance of my Socket Server, where I have events on Accept connection or on error and so on... These events are set in the Application .我已经通过依赖注入设置了 NLog,在一个地方,我注入记录器是我的主要 Class Application ,在这个 class 中,我创建了我的套接字服务器的实例,在那里我有关于接受连接或错误等等的事件......这些事件在Application中设置。

For example the OnAccept event is of course handled by another thread, where is the listening for connection running.例如OnAccept事件当然是由另一个线程处理的,监听连接在哪里运行。 When this event is invoked, everything go as it should, but the logger does not write anything in the log.调用此事件时,所有 go 都应如此,但记录器不会在日志中写入任何内容。 If I use instead of logger Console.WriteLine() , it writes everything, so this event is invoked right (checked even through debug).如果我使用而不是记录器Console.WriteLine() ,它会写入所有内容,因此会正确调用此事件(即使通过调试也可以检查)。

It is something in NLog/ ILogger<> , that it can't write log from another thread?它是 NLog/ ILogger<>中的东西,它不能从另一个线程写入日志? And how to use it in this situation?以及如何在这种情况下使用它?

So, the problem was hidden in fact, I was using DI with creating multiple scopes, so creating through this way doesn't work:所以,问题实际上是隐藏的,我使用 DI 创建多个范围,所以通过这种方式创建是行不通的:

 var serviceCollection = new ServiceCollection();
 serviceCollection.AddLogging(builder =>
 {
    builder.ClearProviders();
    builder.SetMinimumLevel(LogLevel.Trace);
    builder.AddNLog($"{ConfigBasePath}/{NlogConfig}");
});

There are two solutions, create a single shared NLogFactory, and not for every DI container creation, with using static LogManager for setting config file.有两种解决方案,创建单个共享 NLogFactory,而不是为每个 DI 容器创建,使用 static LogManager 设置配置文件。 Or create multiple isolated LogFactory, through this code:或者创建多个隔离的LogFactory,通过这段代码:

var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(builder =>
{
   builder.ClearProviders();
   builder.SetMinimumLevel(LogLevel.Trace);
   builder.AddNLog(serviceProvider => {
       var logFactory = new NLog.LogFactory();
       logFactory.LoadConfiguration($"{ConfigBasePath}/{NlogConfig}");
       return logFactory;
   });
});

My issue on NLog GitHub .我在NLog GitHub上的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM