Conditional Logging?

2 messages Options
Embed this post
Permalink
JayTee

Conditional Logging?

Reply Threaded More More options
Print post
Permalink
We have 3 servers - development, qa, and of course production.

I want the trace/debug messages in dev/qa, but not in production.

I figured there could/would be a quick way to edit the nlog.config file and do kind of a global enable/disable logging below a specified level.  If any issues occurred in production at a later date, I could flip that global switch to enable the more detailed logging until I found the source of the problem after which I could flip the switch back again.

Any way to set a variable like that or am I thinking of this in the wrong way?

Thanks,
Jon
Jaroslaw Kowalski

Re: Conditional Logging?

Reply Threaded More More options
Print post
Permalink
If you want to change global threshold, you can simply use "globalThreshold" attribute on <nlog /> element.

Simply:

<nlog globalThreshold="Info">
    <!-- messages below Info level will not be logged -->
</nlog>

However, by simply lowering log level from Info to say Trace, you may easily get overwhelmed by low-level tracing messages you don't care about. So you will probably find it more convenient to re-enable logging at individual logger or for the entire namespace. To do so, you can add a line like that at the beginning of <rules> section:

<rules>
    <logger name="My.Namespace.*" minLevel="NewLevel" writeTo="targets" final="true" />
    <!-- other rules follow -->
</rules>

It overrides logging for all loggers whose names start with My.Namespace with the new log level being NewLevel. final="true" is there to say that no further rules should be processed for those loggers.

One trick I like to apply whenever I want to keep my logging configuration different for different servers is to use <include />:

You can do this:

NLog.config:

<nlog autoReload="true">
     <targets>
         <!-- define targets here -->
     </targets>
   
    <include file="NLog.${machinename}.config" />

    <rules>
        <!-- define default rules here -->
    </rules>
</nlog>

On top of that need one extra file for each machine where the application is running. With this setup, you can put local overrides in NLog.${machinename}.config where ${machinename} resolves to the name of your machine.

You can try using other layout renderers here as well, and for example use includes based on environment variables:

<include file="${environment:MYLOGFILE}" />

or store included log file name in registry:

<include file="${registry:HKLM\Some\Path:value=MyValue}" />