I'm using NLog 4.7.5 with ASP NET Core 3.1, and would like to set the max log level per HTTP request. My idea is to set MappedDiagnosticsContext within a middleware layer, and apply a dynamic filter. I've done a quick test in LINQPad to demonstrate the filtering.
var appSettings = @"{
""NLog"": {
""throwConfigExceptions"": true,
""targets"": {
""logConsole"": {
""type"": ""Console"",
""layout"": ""${logger} | ${date} | ${level:uppercase=true} | ${message} | ${exception:format=tostring}""
}
},
""rules"": [
{
""logger"": ""*"",
""minLevel"": ""Info"",
""writeTo"": ""logConsole""
}
]
}
}";
var builder = new ConfigurationBuilder();
builder.AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(appSettings)));
var configuration = builder.Build();
MappedDiagnosticsContext.Set("MyLogLevel", LogLevel.Error);
var config = new NLogLoggingConfiguration(configuration.GetSection("NLog"));
config.LoggingRules.First().Filters.Add(
new ConditionBasedFilter
{
// works
Condition = "level < LogLevel.Error",
// does not work
//Condition = "(level < '${mdc:item=MyLogLevel}')",
Action = FilterResult.Ignore
});
var logFactory = new LogFactory(config);
var logger = logFactory.GetCurrentClassLogger();
logger.Info("Informating");
logger.Warn("Warning");
logger.Error("An error");
logger.Debug("Debugging");
logger.Trace("Tracing");
logger.Fatal("A fatal");
However running this, you can see the output from switching the filters around proves the MappedDiagnosticsContext doesn't work.
Static filter
Dynamic filter
My configuration seems valid (no exceptions thrown), however why is this not working? Is there an alternative approach? I considered using a Dependecny Injecting LogFactory and named using loggers, but this approach seems the most straightforward.