Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 368
Dave Hogan Avatar asked Aug 18 '11 12:08

Dave Hogan


People also ask

What can be configured with this NLog config file?

The following types can be configured: Targets - the destinations of a logevent, e.g. file, database, console. Layout - the layout e.g. json, csv, plain-text (default) Layout renderers - the template markers, e.g. ${message}, ${exception}, ${date}

How do I edit NLog config file?

You can find the NLog. config file in {Project Folder}\bin\Debug\net5. 0\ . You can open and edit it as you like with Notepad or Visual Studio.

What is ${ Basedir in NLog?

${basedir} — Directory where the application runs, aka. AppDomain.BaseDirectory. I think, you will find this manual page helpful.


2 Answers

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


}
like image 148
Dave Hogan Avatar answered Sep 17 '22 10:09

Dave Hogan


Updated Answer

NLog ver. 4.6 includes ${appsetting:SmtpHostServer} in the core NLog-nuget-package. No longer requires NLog.Extended. See also https://github.com/nlog/NLog/wiki/AppSetting-Layout-Renderer

NLog.Extensions.Logging ver. 1.4 includes ${configsetting} that allows one to read settings from appsettings.json. See also https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer

Original Answer

Nowadays this is possible without custom code:

Use NLog.Extended and use ${appsetting:SmtpHostServer}.

See docs for ${appsetting}

Please note: this isn't supported in .NET Core / .NET standard yet.

like image 36
Julian Avatar answered Sep 17 '22 10:09

Julian