Search code examples
c#asp.net-corelogging.net-6.0nlog

Stop NLog from logging when I'm debugging the app on my machine


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.


Solution

  • 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>
        <variable 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

    See also: https://github.com/NLog/NLog/wiki/Environment-specific-NLog-Logging-Configuration