You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ConfigSetting Layout Renderer不符合文档预期的问题排查

.NET6 API中NLog无法从appsettings读取连接字符串问题
  • 已严格按照NLog ConfigSetting Layout Renderer文档操作,但无法从appsettings.json中获取连接字符串。硬编码连接字符串时NLog功能正常,说明相关依赖库已正确配置。
  • 将文档提供的代码放置在.NET6 API的Program.cs中(代码如下),但在nlog.config中配置connectionString="${configsetting:item=ConnectionStrings.PostgreSQL}"(也尝试用name替代item)时,始终报错The ConnectionString property has not been initialized。
  • 疑问:是否必须使用代码中创建的logger变量才能让ConfigSetting生效?目前使用的是日志抽象库的构造注入方式(代码如下),该方式在其他日志场景下工作正常。

Program.cs代码

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>()
                    .ConfigureLogging((context, logging) =>
                    {   // 文档中的代码 - 是不是只有用这个logger变量日志才生效?
                        var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();                            
                        logging.AddNLog(context.Configuration.GetSection("Logging"));
                    });
            });
}

nlog.config配置

connectionString="${configsetting:item=ConnectionStrings.PostgreSQL}"

构造注入代码

public MyController(ILogger<ActivitiesController> log)
{
    _log = log;
}

[HttpGet("test")]   
public async Task<ActionResult<IList<ADto>>> Table()     
{
    _log.LogInformation("Loading something..."); 
    // ...其他代码
}

内容的提问来源于stack exchange,提问作者PandaWood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 12:22:43