Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
/NLogPublic

Filtering log messages

Rolf Kristensen edited this pageAug 9, 2025 ·43 revisions

Log messages may be filtered via eitherrouting orfiltering.

Routing

Logging Rules is the most efficient way to perform filtering using the name of the Logger. By skipping the allocation ofLogEventInfo-objects, when no output is needed.

One can silence a noisy loggger by redirecting it to a "blackhole" by not specifyingwriteTo= for the logging-rule. But if also needing custom filter logic, then one needs to use aNull target.

NLog 4.5 made it possible to specify emptywriteTo="", but when using older versions thenNull target must be used.

<rules><!-- ignore events written that are written to a logger which starts with "Namespace."-->   <loggername="Namespace.*"minlevel="Trace"final="true" /><!-- BlackHole that swallows everything-->   <loggername="Namespace.*"maxLevel="Info"final="true" /><!-- BlackHole that swallows non-critical--></rules>

NLog v5 introduced theFinalMinLevel-option, becauseMaxLevel was causing a lot of headache and confusion.

<rules><!-- ignore events written that are written to a logger which starts with "Namespace."-->   <loggername="Namespace.*"finalMinLevel="Off" /><!-- BlackHole that swallows everything-->   <loggername="Namespace.*"finalMinLevel="Warn" /><!-- BlackHole that swallows non-critical--></rules>

Filters

With the use of<filters> then you can inspect the actual log-events and decide to ignore (blacklist) and/or allow (whitelist) the events. See also<when> filter.

e.g.

<loggername="*"writeTo="file">  <filtersdefaultAction="Log">    <whencondition="length('${message}') > 100"action="Ignore" />  </filters></logger>

ThedefaultAction-option was introduced with NLog 4.6. Before NLog 5.0 then the default value wasNeutral.

Note filters gives a performance penalty, because NLog LogEventInfo objects will be allocated upfront even if discarded by filter-result.

Example in C#

The above configuration can be implemented directly in C# like this:

varconfig=LogManager.Configuration;// some targetvarfileTarget=newFileTarget();// set-up rule with filtervarloggingRule=newLoggingRule("*",fileTarget);loggingRule.FilterDefaultAction=FilterResult.Log;loggingRule.Filters.Add(newConditionBasedFilter(){Condition="length('${message}') > 100",Action=FilterResult.Ignore});config.LoggingRules.Add(loggingRule);// apply configLogManager.Configuration=config;

With NLog 5.0 then one can also do this:

NLog.LogManager.Setup().LoadConfiguration(builder=>{builder.ForLogger().FilterDynamicIgnore(evt=>evt.FormattedMessage?.Length>100).WriteToFile("log.txt");});

Global Threshold

LogManager.GlobalThreshold can be assigned a LogLevel, and then only LogEvents with same severity (or higher) will be logged.

LogManager.GlobalThreshold will overrule the configuration of logging rules. If logging rules saysminLevel="Debug" thenLogManager.GlobalThreshold = LogLevel.Error will still win.

if(IsProduction)NLog.LogManager.GlobalThreshold=NLog.LogLevel.Info;elseNLog.LogManager.GlobalThreshold=NLog.LogLevel.Trace;// No global filter

Null Logger

LogManager.CreateNullLogger() will return a Logger-instance that will not generate any output.

This can be used to silence certain components without depending on the NLog-configuration.

varlogger=IsProduction?LogManager.CreateNullLogger():LogManager.GetCurrentClassLogger();logger.Info("No output when in production");

DEBUG build only

The .NET compiler has the ability to remove DEBUG-code when making Release-build. This means only Debug-build will give output, when using these conditional logging methods:

  • Logger.ConditionalTrace - Performs logging using NLogLogLevel.Trace
  • Logger.ConditionalDebug - Performs logging using NLogLogLevel.Debug
_logger.ConditionalDebug("DEBUG build only output");

It is shorthand of doing this:

#ifDEBUG_logger.Debug("DEBUG build only output");#endif

Semi Dynamic Routing Rules

Routing rules are more efficient than using dynamic filters, and the performance comes from static nature of the rules. NLog 4.6.7 introduced the ability to use Layout-logic for controlling LogLevel in the logging-rules, that can be explicitly refreshed.

<nlog>   <variablename="myLevel"value="Warn" />    <rules>      <loggerminLevel="${var:myLevel}"writeTo="file" />    </rules></nlog>

Then NLog 4.6.7 allows you to do this:

#ifDEBUGLogManager.Configuration.Variables["myLevel"]="Debug";LogManager.ReconfigExistingLoggers();// Explicit refresh of Layouts and updates active Logger-objects#endif

It is possible to disable logging output completely by usingminLevel="Off" for the logging-rule.

Possible use-case could be to activate special debug-mode, that changes the loglevel-variable as shown above, and then schedules a timer to restore default-level to "Warn" after 5 mins.

Environment Specific Filtering

There is a dedicated wiki-page for how to setupEnvironment specific NLog Logging Configuration so Production- and Development-environment can have different output-levels and destination targets.

Fully Dynamic Filtering

The Semi Dynamic Routing Rules improves the combination of NLog configuration loaded from config-file, and adjusting NLog configuration at runtime.

When NLog configuration is created at runtime alone, then one have access to even more dynamic filtering logic capabilities. Ex. by usingNLog.Filters.WhenMethodFilter:

config.LoggingRules.Last().Filters.Add(newWhenMethodFilter(logEvent=>ShouldIgnoreLogEvent(logEvent)?FilterResult.Ignore:FilterResult.Log));

It is also possible to use theNLog.Config.LoggingRule constructor that specifiesRuleName. Where it is possible to lookup the LoggingRule usingLoggingConfiguration.FindRuleByName when needing to adjust it.

Deprecated filters

These filters are deprecated. They have been replace by the<when> filter, which exposes uses modifiable conditions for filtering log events.

-Troubleshooting Guide - See available NLog Targets and Layouts:https://nlog-project.org/config

Configuration

Programmatic Configuration

Advanced

Extending NLog

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp