'NLog Configuration specifically for .net core 3.1 specifying the nlog file by name/env, and enabling DI
How can I configure an asp.net core 3.1 application to use NLog, specifically setting a custom log filename (i.e. nlog.[environment].config, and also enable for DI. I have tried many things without success.
I know there are a lot SO questions and online articles about nlog configuration, but I cannot seem to find an example for my specific scenario and requirements. I am open to using altermative methods such as configuring via appsettings.[env].json, but want to avoid multiple web.config files
One example of what I have tried:
public static void Main(string[] args)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var logFile = "nlog.config";
if (environment.Contains("Debug") || environment.Contains("Local"))
logFile = "nlog.debug.config";
// logger works only in Main() method, not as DI
var logger = NLogBuilder.ConfigureNLog(logFile).GetCurrentClassLogger();
logger.Info("Starting My App");
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.Sources.Clear();
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
...
.ConfigureLogging((hostingContext, logging) =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug);
logging.AddConsole();
})
.UseNLog(config); // << config has error, I can't seem to find a way to instanciate config.
}
Solution 1:[1]
It's a little tricky. I have two NLog config files besides my main NLog config file. Those files are nlog.Production.config and nlog.NonProduction.config. In the main NLog file I'm using this line:
<include file="nlog.${when:when='${environment:ASPNETCORE_ENVIRONMENT}'=='Production':inner=Production:else=NonProduction}.config" />
Depending on the environment, one of those files is included.
See also: https://github.com/NLog/NLog/wiki/XML-config-include-Example
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rolf Kristensen |
