I use NLog for writing logs on my Web API apps, (.Net 6)
And I needed to write to the log inside the ConfigureServices method.
Since ILogger is not available at this point, I used this way to write to the log:
var logger = LogManager.GetCurrentClassLogger();
logger.Log(NLog.LogLevel.Debug, "my data");
It works and is written properly to the log,
But the problem is that if this code exists, throughout the application and in all subsequent requests, the ${aspnet-request-url} and ${aspnet-mvc-action} properties appear empty in the log.
If I remove this code - they appear full in all the requests.
I tried to change the way of writing to the log to something else:
var sp = services.BuildServiceProvider();
var logger = sp.GetService<ILogger<Startup>>();
logger.LogDebug("my data");
It also writes correctly, but the problem with both properties ${aspnet-request-url} and ${aspnet-mvc-action} remains the same, both appear empty.
My question is:
How is it possible on the one hand to write to the log by NLog in the ConfigureServices method,
And on the other hand, not to lose the two ${aspnet-request-url} and ${aspnet-mvc-action} properties?
p.s.
I want to point out again that they are empty in all the requests that happen afterwards,
not only in this writing from the ConfigureServices method.
When calling LogManager.GetCurrentClassLogger()
very early during application-startup, before UseNLog()
have automatically registered NLog.Web-extensions, then one is required to do it manually.
Either ensure NLog.config
-file register extensions like this:
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
Alternative register extensions from code like this:
var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
When troubleshooting issues with NLog, then it is recommended to use NLog InternalLogger and look for clues, along with using throwConfigExceptions="true"
. See also: https://github.com/NLog/NLog/wiki/Logging-troubleshooting
Notice Startup.cs
and ConfigureServices
seems to be legacy from NET5 (and older). With NET6 then Microsoft started to sell a different approach: https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-6