Unable to set my connectionstring in NLog

时间秒杀一切 提交于 2019-12-03 11:49:39
Julian

Updated answer

Since NLog.Web.AspNetCore 4.8 (NLog.Extensions.Logging 1.4 for .NET Core console programs) you could directly read from your appSettings.json

${configsetting:name=MyConnectionString}

see docs


Original answer

Unfortunately reading connectionstrings/settings from appSettings.json / app.config is not yet supported in NLog for .NET core.

Two options:

  1. Set the connectionstring programmatically, by using variables. In your nlog.config:

    <target ... connectionString="${var:myConnectionstring}"  ... />
    

    and in code: (e.g. in Configure)

    LogManager.Configuration.Variables["myConnectionstring"] = "...."; //read config here
    
  2. Or, set the connectionstring in nlog.config.

    In your nlog.config:

    <variable name="myConnectionstring" value="...." />  
    

    and using in your target in nlog.config:

    <target ... connectionString="${var:myConnectionstring}" ... />
    

Another option is to create and register a custom NLog layout-renderer (startup.cs):

https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer

Which outputs the ConnectionString after having read it from your favorite configuration-location. Then you don't have the connectionstring in your nlog.config, but just refer to your custom layout-renderer.

Maybe cheer for this pending issue:

https://github.com/NLog/NLog.Web/issues/107

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!