.net-coreconfigurationnlog

NLog can't read app.config configSection in .NET Core 2.2 console app


I am troubleshooting an issue where NLog isn't loading it's configuration from the App.config in a .NET Core 2.2 console application.

When calling NLog.LogManager.GetCurrentClassLogger() the resulting object is blank and has no logging targets or other configuration.

<appSettings> configuration items can be looked up without issue using the usual method: ConfigurationManager.AppSettings["settingKey"].

In the process of trying to figure this out, I called ConfigurationManager.GetSection("nlog") to just see if I could get the settings manually. This threw the following exception:

System.Configuration.ConfigurationErrorsException: 
'An error occurred creating the configuration section handler for nlog: 
Could not load type 'NLog.Config.ConfigSectionHandler' from assembly 'NLog'

The entire app.config from my sample app looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>
  <appSettings>
    <add key="value1" value="TEST1"/>
    <add key="value2" value="TEST2"/>
  </appSettings>
  <nlog>
    <targets>
      <target name="logfile" type="File" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" />
      <target name="logconsole" type="Console" />
    </targets>
    <rules>      
      <logger name="*" minlevel="Info" writeTo="logconsole"/>
      <logger name="*" minlevel="Info" writeTo="logfile"/>
    </rules>
  </nlog>
</configuration>

NLog is version 4.6.7 from nuget.


Solution

  • In case anyone else runs into this:

    Since NLog doesn't support app.config in .NET Core, my solution was to create a separate nlog.config (with SlowCheetah environment transforms) and run NLog.LogManager.LoadConfiguration(".\\nlog.config"); at the beginning of the application.

    I'll set this as the answer unless someone rolls through with a clever workaround for keeping things all in the one config.