0
votes

I've configured nlog to write logs to database, giving host for connection string from appsettings.json using config layout drawer. But there are some log calls inside Startup.ConfigureServices and Startup.Configure. So, when the configuration is not ready, nlog in this moment tries to write to database. It takes empty host (config is still not ready!), and in the nlog's own log file I see the error of failed logging because of empty host.

So, the question: is it the way not to log to database target utill the config will be ready?

1

1 Answers

1
votes

I'm guessing the issue is that you start using NLog before having loaded MEL-Configuration.

The "solution" is to perform early load and setup the appsettings.json:

var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    .AddEnvironmentVariables();

Configuration = builder.Build();

ConfigSettingLayoutRenderer.DefaultConfiguration = Configuration;

// Loads NLog.config one more time
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

See also: https://github.com/NLog/NLog.Extensions.Logging/issues/265

NLog 4.7.1 and NLog.Web.AspNetCore ver. 4.9.3 will make it possible to do this:

var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();

See also: https://github.com/NLog/NLog.Web/pull/540