I have a .Net 6 Web API which is using NLog (version 5.0.2). Currently, when an unhandled exception occurs, it is being logged, regardless of the machine the Web API is running on. I'd like it to only log these unhandled exceptions when the API is hosted on our hosting server (in our case, Azure App Service) and not when I am debugging the API locally on my machine.
I've Googled this but have found nothing. I thought there could perhaps be some filter based on a layout such as "{machinename}", so i could say if {machinename} = 'mypc', then don't log. But as far as I can see, there's no such thing.
Any suggestions? Thank you.
CodePudding user response:
Here is a previous question that may provide some relevant information: How do I specify NLog's config by environment using core dependency injection?
You will likely need to implement some sort of system to identify the environment to your application, most likely an environmental variable. From there you have several options for handling this for example you could configure your logging framework to only log to certain outputs in production vs development or you could implement exception handling middleware to handle exceptions differently for different environments.
Luckily ASP.NET 6 handles this fairly well out of the box and it is not unusual behavior so most of the tools are well documented to do this, most likely you'll be setting the ASPNETCORE_ENVIRONMENT
environmental variable on your local machine vs the deployed production machine and then using that value to change the behavior of your application
I recommend checking out these resources:
CodePudding user response:
I'm guessing the issue is not that the LogEvent occurs, but that it is sent to a special target, that should not be used when debugging locally.
Instead of having multiple environment specific NLog.config-files, then you could also do this at startup:
internal static class Program
{
private static void Main()
{
#if DEBUG
// First thing
NLog.GlobalDiagnosticsContext.Set("DebugLogLevel", "Off");
NLog.LogManager.ReconfigureExistingLoggers();
#endif
// Everything else as usual
}
}
The NLog.config can then skip logging to your special target when debugging:
<nlog>
<variables key="DefaultLogLevel" value="${gdc:DebugLogLevel:whenEmpty=Info" />
<rules>
<logger name="*" minLevel="${DefaultLogLevel}" writeTo="SpecialTarget" />
</rules>
</nlog>
See also: https://github.com/NLog/NLog/wiki/Filtering-log-messages#semi-dynamic-routing-rules