与 Microsoft.Extensions.DependencyInjection 一起使用时是否可以以编程方式配置 NLog?

Is it possible to programmatically configure NLog when used with Microsoft.Extensions.DependencyInjection?

我在我的项目中使用 Microsoft.Extensions.DependencyInjection 并希望使用 Microsoft.Extension.Logging,并将 NLog 作为实际的日志记录框架。

因为我希望能够以编程方式决定启动时的日志记录配置(以解决路径问题),所以我正在做这样的事情:

var config = new LoggingConfiguration();
var dirPath = Path.Combine(publicStorage, "Test");
var logFileTarget = new NLog.Targets.FileTarget()
{
    CreateDirs = true,
    FileName = Path.Combine(dirPath, "test.log"),
    FileNameKind = NLog.Targets.FilePathKind.Absolute,
    Layout = "${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}",
    Name = "FileLog",
};

//Add Logging Targets
config.AddTarget(logFileTarget);

//Add Rules
config.AddRuleForAllLevels(logFileTarget, "*", false);

LogManager.Configuration = config;

但这不会配置 ServiceProvider.GetService<ILogger<T>> 返回的那些记录器。 但是,如果我使用 LogManager.GetLogger("TestLogger") 日志记录的配置符合预期。

LogManager.ReconfigExistingLoggers(); 也没有解决问题,我的搜索结果为空

编辑

DI 设置如下所示:

return new ServiceCollection()
    // Configure Logging Provider
    .AddLogging(builder =>
    {
        builder.AddDebug();
        //Add NLog
        builder.AddNLog(new NLogProviderOptions()
        {
            CaptureMessageTemplates = true,
            CaptureMessageProperties = true,
        });
    })
... // Registering additional dependencies
.BuildServiceProvider();

Using LogManager.GetCurrentClassLogger gives the same "incorrect behaviour" as seen with the Loggers returned by serviceProvider. Since the rule is setup with "*" I would have expected that all loggers including those using class names are caught by this rule

这最后一句不正确它实际上是有效的,但仍然存在 di 消息不出现 ILogger

记住遗漏:

builder.SetMinimumLevel(LogLevel.Trace);

另见 wiki:https://github.com/NLog/NLog.Extensions.Logging/wiki/Getting-started-with-.NET-Core-2---Console-application#32-setup-the-dependency-injector-di-container