NLog config file to get configuration setting values from a web.config

Dave Hogan picture Dave Hogan · Aug 18, 2011 · Viewed 8.6k times · Source

Is there a method to get a value from the <ApplicationSettings> section of a web.config within NLog layout variables?

I already store SMTP details within my web.config and don't want to duplicate the settings just to use within my NLog.config.

Ideally I'd like to do something like: ${aspnet-config:SmtpHostServer} which then fetches the value from the web.config

Answer

Dave Hogan picture Dave Hogan · Aug 18, 2011

I couldn't see any obvious way to do this other than creating my own LayoutRenderer (see below). If you're putting into your own assembly don't forget to add the following into your NLog.Config:

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

Hope this helps someone else:

[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));
    }


}