有没有一种方法可以从web.config的部分中获取值并将其用于NLog布局变量?
我已经在web.config中存储了SMTP详细信息,不想复制设置以在我的NLog.config中使用。
理想情况下,我想要做的是: ${aspnet-config:SmtpHostServer}
,然后从web.config中获取该值。
有没有一种方法可以从web.config的部分中获取值并将其用于NLog布局变量?
我已经在web.config中存储了SMTP详细信息,不想复制设置以在我的NLog.config中使用。
理想情况下,我想要做的是: ${aspnet-config:SmtpHostServer}
,然后从web.config中获取该值。
除了创建自己的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));
}
}
更新后的答案
NLog 4.6 版本在核心NLog-nuget包中包含了${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}
.
请注意:目前还不支持.NET Core / .NET standard。