【问题标题】:NLog config file to get configuration setting values from a web.configNLog 配置文件从 web.config 获取配置设置值
【发布时间】:2011-08-18 12:35:05
【问题描述】:

有没有一种方法可以从 NLog 布局变量中的 web.config 的 <ApplicationSettings> 部分获取值?

我已经在我的 web.config 中存储了 SMTP 详细信息,并且不想复制这些设置只是为了在我的 NLog.config 中使用。

理想情况下,我想做这样的事情:${aspnet-config:SmtpHostServer} 然后从 web.config 中获取值

【问题讨论】:

    标签: web-config nlog appsettings


    【解决方案1】:

    除了创建自己的LayoutRenderer(见下文)之外,我看不到任何明显的方法可以做到这一点。如果您要放入自己的程序集,请不要忘记将以下内容添加到您的 NLog.Config 中:

    <extensions>
       <add assembly="YOURASSEMBLYNAMEHERE" />
    </extensions>
    

    希望这对其他人有所帮助:

    [LayoutRenderer("aspnet-config")]
    public class AspNetConfigValueLayoutRenderer : LayoutRenderer
    {
        [DefaultParameter]
        public string Variable
        {
            get;
            set;
        }
    
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            if (this.Variable == null)
            {
                return;
            }
            HttpContext context = HttpContext.Current;
            if (context == null)
            {
                return;
            }
            builder.Append(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings[this.Variable], CultureInfo.InvariantCulture));
        }
    
    
    }
    

    【讨论】:

      【解决方案2】:

      更新答案

      NLog 版本。 4.6 在核心 NLog-nuget-package 中包含 ${appsetting:SmtpHostServer}。不再需要 NLog.Extended。另见https://github.com/nlog/NLog/wiki/AppSetting-Layout-Renderer

      NLog.Extensions.Logging 版本。 1.4 包括${configsetting},它允许从 appsettings.json 读取设置。另见https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer

      原答案

      如今,无需自定义代码就可以做到这一点:

      使用NLog.Extended 并使用 ${appsetting:SmtpHostServer}.

      见docs for ${appsetting}

      请注意:.NET Core / .NET 标准尚不支持此功能。

      【讨论】:

      • 感谢分享@Julian - 了解有用。我已经更改了日志记录提供程序。
      猜你喜欢
      • 2011-03-08
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多