Search code examples
c#azurenlog

NLog config file - pull value from WebConfig/App service config


.Net Framework 4.8 application running on an App Service.

(The project currently has all below Nuget packages installed for NLog)

NLog 4.7.15
NLog.Config 4.5.9
NLog.Extended 4.5.9
NLog.Web 4.6.0
NLog.Schema 4.5.9

So say we have a value in the app settings and connection string of web.config

 <connectionStrings>
    <add name="ElasticUrl" connectionString="http://localhost:9200"/>
  </connectionStrings>
    <appSettings>
        <add key="testRobot" value="12345" />
        </appSettings>

My question is it is possible to obtain these values inside the NLog.config file

So for example in the Nlog file we are setting the date with

  <parameter name="@logged" layout="${date}" />

is it possible to say something like

  <parameter name="@logged" layout="${ConfigurationManager.AppSettings["testRobot"]}" />

thanks for any replies

UPDATE

Thank you to @Harshitha and @Rolf Kristensen for taking the time to reply.

I was able to get it working (for appsettings value) but with a slight different to what is suggested in the documentation where they use 'item' to retrieve the contents but I had to use 'name'

https://github.com/NLog/NLog/wiki/AppSetting-Layout-Renderer

 <parameter name="@message" layout="${appsetting:name=testRobot:default=default}" />

will store the value 12345 in the message.

However, this did not work for connection string...which according to the documentation (link just provided) if I have a

<configuration>
  <appSettings>
    <add key="MyKey" value="MyApplication" />
  </appSettings>
  <connectionStrings>
    <add name="ElasticUrl" connectionString="http://localhost:9200"/>
  </connectionStrings>
</configuration>

I should be able to say:

${appsetting:item=connectionStrings.ElasticUrl}

this did not work, failing with: Required parameter 'Name' on 'Layout Renderer: ${appsetting}' was not specified.

nor did:

 ${appsetting:name=connectionStrings.ElasticUrl}

which didnt throw an exception but saved the message as an empty string value??

and also just an observation but why are we using $(appsetting when the connection string values arnt inside the appsetting tag

any help please?


Solution

  • You can use ${appsetting}, see also List of available Layout Renderers

    ${appsetting:name=testRobot:default=default}
    

    Notice when using NLog v4.6.5 (or newer), then one can also resolve ConnectionStings-values like this:

    ${appsetting:item=connectionStrings.ElasticUrl}
    

    And retrieve value from app.config-file like this:

    <configuration>
      <appSettings>
        <add key="MyKey" value="MyApplication" />
      </appSettings>
      <connectionStrings>
        <add name="ElasticUrl" connectionString="http://localhost:9200"/>
      </connectionStrings>
    </configuration>
    

    Make sure to remove nuget-package NLog.Extended from your application-project when upgrading to NLog v4.6.5 (or newer).