NLog 忽略 MVC 控制器中的 appsettings.json

NLog ignores appsettings.json within an MVC controller

根据 documentation 我将我的应用程序设置为使用 NLog 进行日志记录:

IHost host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder()
    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.CaptureStartupErrors(true);
        webBuilder.UseSetting(WebHostDefaults.PreventHostingStartupKey, "true");
        webBuilder.UseStartup<Startup>();
        webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
    })
    .ConfigureLogging((context, logging) =>
    {
        var configuration = context.Configuration.GetSection("NLog");
        if (configuration.Exists())
            NLog.LogManager.Configuration = new NLogLoggingConfiguration(configuration);
        logging
            .ClearProviders()
            .SetMinimumLevel(LogLevel.Trace);
    })
    .UseNLog()
    .Build();
host.StartAsync();

在构建 host 之后,LogManager.Configuration 对应于我的 appsettings.jsonNLog 部分。但是它在控制器中包含 null,因此控制器不写入日志。该日志仅包含以下记录:

2022-02-21 10:16:46.6273 INFO Microsoft.Hosting.Lifetime Now listening on: ...
2022-02-21 10:16:46.6498 INFO Microsoft.Hosting.Lifetime Application started. Press Ctrl+C to shut down.
2022-02-21 10:16:46.6498 INFO Microsoft.Hosting.Lifetime Hosting environment: Development
2022-02-21 10:16:46.6498 INFO Microsoft.Hosting.Lifetime Content root path: ...

有趣的是,内部日志显示在主机停止之前记录器已关闭:

2022-02-21 10:16:35.8017 Info Auto loading assembly file: ...\bin\Debug\net5.0\NLog.Extensions.Logging.dll
2022-02-21 10:16:35.8017 Info Loading assembly file: ...\bin\Debug\net5.0\NLog.Extensions.Logging.dll
2022-02-21 10:16:35.8187 Info NLog.Extensions.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 1.7.4.1610. Product version: 1.7.4+e2bffa9e949fb4760d75aca224e78631c063f087. GlobalAssemblyCache: False
2022-02-21 10:16:35.8187 Info Auto loading assembly file: ...\bin\Debug\net5.0\NLog.Extensions.Logging.dll succeeded!
2022-02-21 10:16:35.8187 Info Auto loading assembly file: ...\bin\Debug\net5.0\NLog.Web.AspNetCore.dll
2022-02-21 10:16:35.8284 Info Loading assembly file: ...\bin\Debug\net5.0\NLog.Web.AspNetCore.dll
2022-02-21 10:16:35.8284 Info NLog.Web.AspNetCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.14.0.2042. Product version: 4.14.0+18bbcdbd5bd13b4565c32d72e09502b7ca6c71d4. GlobalAssemblyCache: False
2022-02-21 10:16:35.8284 Info Auto loading assembly file: ...\bin\Debug\net5.0\NLog.Web.AspNetCore.dll succeeded!
2022-02-21 10:16:35.8284 Info Message Template Auto Format enabled
2022-02-21 10:16:35.8549 Info Adding target FileTarget(Name=file)
2022-02-21 10:16:35.8634 Info Validating config: TargetNames=file, ConfigItems=18
2022-02-21 10:16:46.6575 Info AppDomain Shutting down. Logger closing...
2022-02-21 10:16:46.6575 Info Logger has been shut down.

为什么应用程序继续执行时显示“AppDomain Shutting down”?

如果我使用 nlog.config 而不是 appsettings.json,日志记录工作正常,但我必须配置NLog appsettings.json。所以,我需要你的帮助来解决这个问题。

您可以像这样将 NLog 配置为依赖于 Microsoft LoggerFactory 的生命周期:

.ConfigureLogging((context, logging) =>
{
    NLog.LogManager.AutoShutdown = false; // Unhook from AppDomain, to depend on host
    var configuration = context.Configuration.GetSection("NLog");
    if (configuration.Exists())
        NLog.LogManager.Configuration = new NLogLoggingConfiguration(configuration);
    logging
        .ClearProviders()
        .SetMinimumLevel(LogLevel.Trace);
})
.UseNLog(new NLogAspNetCoreOptions() { ShutdownOnDispose = true }) // Depend on Host
.Build();

重要的设置是AutoShutdownShutdownOnDispose。使用 NLog.Web.AspNetCore v5.0 时将默认配置设置。