【问题标题】:NLog from appsettings with custom appsettings来自 appsettings 的 NLog 和自定义 appsettings
【发布时间】:2020-12-10 22:15:13
【问题描述】:

我有一个需要添加到配置中的自定义 appsettings JSON 文件。我在从 Program.cs 中的 Main 调用的 CreateHostBuilder 调用的 ConfigureAppConfiguration 挂钩中执行此操作。我也在使用 NLog。

public static void Main(string[] args)
{
    //
    // currently using nlog.config but I want to use appsettings but they haven't been "built" yet
    var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    try
    {
        logger.Debug("init main");
        CreateHostBuilder(args).Build().Run();
        // could move configurenlog call here, but already called "UseNLog()"
    }
    catch (Exception exception)
    {
        logger.Error(exception, "Stopped program because of exception");
        throw;
    }
    finally
    {
        NLog.LogManager.Shutdown();
    }
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration((hostingContext, config) => {
                  // add custom config file
                    config  
                        .AddJsonFile("customsettings.json", optional:true, reloadOnChange:true);
                })
      .ConfigureWebHostDefaults(webBuilder =>
      {
          webBuilder.UseStartup<Startup>();
      })
      .ConfigureLogging(logging =>
      {
          logging.ClearProviders();
          logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
      })
      .UseNLog();  // NLog: Setup NLog for Dependency injection

现在我想使用(组合的)appsettings 来配置 nlog as outlined here,但是在我加载了我的自定义配置设置之后我该怎么做呢?

【问题讨论】:

  • 可以在控制器中生成日志吗?

标签: c# .net-core nlog appsettings


【解决方案1】:

您可以在 CreateHostBuilder 之前调用 LoadConfigurationFromAppSettings() 加载 appsettings:

using NLog;
using NLog.Web;

public static void Main(string[] args)
{
    var logger = LogManager.Setup()
                           .LoadConfigurationFromAppSettings()
                           .GetCurrentClassLogger();
    try
    {
        logger.Debug("init main");
        CreateHostBuilder(args).Build().Run();
    }
    catch (Exception exception)
    {
        logger.Error(exception, "Stopped program because of exception");
        throw;
    }
    finally
    {
        NLog.LogManager.Shutdown();
    }
}

另请参阅:https://github.com/NLog/NLog.Web/blob/master/examples/ASP.NET%20Core%203/ASP.NET%20Core%203%20-%20VS2019/Program.cs

【讨论】:

  • 不幸的是,这不会加载我的 customsettings.json 文件。我正在尝试将数据库连接放在自定义 appsettings 文件中。我可以模仿“LoadConfigurationFromAppSettings”并添加我的 customsettings.json 文件,但我已经在“ConfigureAppConfiguration”中执行此操作,并且希望此时仅获取配置而不是两次执行相同的操作。 github.com/NLog/NLog.Web/blob/…
  • 看来我应该在 Startup 中执行此操作
  • 如果您想在创建 HostBuilder 之前登录并运行,那么您需要加载配置两次。但是,如果您可以在 HostBuilder 运行之前不使用 NLog,那么只需从您的主方法中删除除CreateHostBuilder 和最后的NLog.LogManager.Shutdown() 之外的所有内容。
【解决方案2】:

您可以在主机构建过程中(在ConfigureServices()中)获取配置(包括您的customsettings.json),并使用它来配置NLog。

为了简化/避免用于存储配置的变量的范围问题,我将 CreateHostBuilder() 方法移到 Main() 主体中:

public static void Main(string[] args)
{
    NLog.Logger theLogger = null;
    try
    {
        Microsoft.Extensions.Configuration.IConfiguration theConfig = null;

        var theHostBuilder = Host.CreateDefaultBuilder(args)
             .ConfigureAppConfiguration((hostingContext, config) =>
             {
                 // add custom config file
                 config.AddJsonFile("customsettings.json", optional: true, reloadOnChange: true);
             })
            .ConfigureServices((hostContext, services) =>
            {
                // store the configuration (includes your 'customsettings.json') in a variable
                theConfig = hostContext.Configuration;
            })
            .ConfigureLogging(l =>
            {
                l.ClearProviders();
                l.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            })
            .UseNLog();

        // Build the host (actually executes the lambdas in .ConfigureAppConfiguration, .ConfigureServices, etc.)
        var theHost = theHostBuilder.Build();

        // configure NLog using the configuration obtained above
        NLog.LogManager.Configuration = new NLog.Extensions.Logging.NLogLoggingConfiguration(theConfig.GetSection("NLog"));
        
        // obtain the logger
        theLogger = NLog.LogManager.GetCurrentClassLogger();

        theHost.Run();
    }
    catch (Exception ex)
    {
        // if the logger could be obtained, log the exception
        theLogger?.Error(ex, "Exception!");
    }
    finally
    {
        NLog.LogManager.Shutdown();
    }
}

我的想法来自here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 2016-09-23
    • 2023-04-06
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 2011-08-15
    相关资源
    最近更新 更多