Skip to content
Rolf Kristensen edited this page Jul 30, 2022 · 27 revisions

Filter events in the config.

Platforms Supported: All

Configuration Syntax

<rules>
  <logger ... >
    <filters defaultAction="Neutral | Ignore | Log | LogFinal | IgnoreFinal">
      <when condition="Condition" action="Enum"/>
    </filters>
  </logger>
</rules>

Parameters

  • defaultAction - default filter action when no match. Default Ignore.

    Introduced with NLog 4.6. Before NLog 5.0 the default was Neutral.

    • Ignore - The message should not be logged.
    • IgnoreFinal - The message should not be logged and ignore any following logging-rules.
    • Log - The message should be logged.
    • LogFinal - The message should be logged and ignore any following logging-rules.
    • Neutral - No decision
  • filterdefaultaction - Alternative name for defaultAction to match actual API.

    Introduced with NLog 5.0

Filtering Options

  • condition - Condition expression. Condition Required. See section Conditions below.
  • action - Action to be taken when filter matches. Required.
    Possible values:
    • Ignore - The message should not be logged.
    • IgnoreFinal - The message should not be logged and ignore any following logging-rules.
    • Log - The message should be logged.
    • LogFinal - The message should be logged and ignore any following logging-rules.
    • Neutral - The filter doesn't want to decide whether to log or discard the message.

Conditions

Conditions are expressions used with the <when> filter. They consist of one or more tests. They are used in the filter to determine if an action will be taken.

Predefined Tokens

  • message - LogEvent formatted message
  • logger - Logger name
  • level - LogLevel object
  • exception - Exception object (Introduced with NLog 5.0)
  • ${layout} - All available layout-options (except stacktrace).

Condition Language

The filter expressions are written in a special mini-language. The language consists of:

  • relational operators: ==, !=, <, <=, >= and >
    Note: Some predefined XML characters may need to be escaped. For example, if you try to use the '<' character, the XML parser will interpret it as an opening tag which results in an error in the configuration file. Instead, use the escaped version of '<' (&lt;) in this context.
  • boolean operators: and, or, not
  • string literals which are always evaluated as layouts - ${somerenderer}
  • boolean literals - true and false
  • numeric literals - e.g. 12345 (integer literal) and 12345.678 (floating point literal)
  • log level literals - LogLevel.Trace, LogLevel.Debug, ... LogLevel.Fatal
  • predefined keywords to access the most common log event properties - level, message and logger
  • braces - to override default priorities and group expressions together
  • condition functions - to perform string and object tests
  • Single quotes should be escaped with another single quote.

Condition Functions

The following condition functions are available:

  • contains(s1,s2) Determines whether the second string is a substring of the first one. Returns: true when the second string is a substring of the first string, false otherwise.
  • ends-with(s1,s2) Determines whether the second string is a suffix of the first one. Returns: true when the second string is a prefix of the first string, false otherwise.
  • equals(o1,o2) Compares two objects for equality. Returns: true when two objects are equal, false otherwise.

    Notice that 'o1' == 'o2' or 'o1' != 'o2' will be faster and reduces memory allocations.

  • length(s) Returns the length of a string.

    Notice that 's' != '' is faster than length('s') > 0, and reduces memory allocation.

  • starts-with(s1,s2) Determines whether the second string is a prefix of the first one. Returns: true when the second string is a prefix of the first string, false otherwise.
  • regex-matches(input, pattern, options) Introduced in NLog 4.5. Indicates whether the regular expression pattern finds a match in the specified input string. options is an optional comma separated list of values from the RegexOptions enumeration.
    Returns : true when a match is found in the input string, false otherwise.
    Example : regex-matches('${message}', '^foo$', 'ignorecase,singleline')

Quotes

Single quotes should be escaped with another single quote. Example:

contains('${message}', 'Cannot insert the value NULL into column ''Col1')

Extensibility

New custom condition functions methods can also be added.

NLog 4.7 allows you to register your own condition methods using LogFactory.Setup(). Where a lambda can be registered like this:

LogManager.Setup().SetupExtensions(s => 
   s.RegisterConditionMethod("hasParameters", evt => evt.Parameters?.Length > 0)
);

And a static method like this:

LogManager.Setup().SetupExtensions(s =>
   s.RegisterConditionMethod("hasPriority", typeof(NLogConditionMethods).GetMethod("HasPriority", BindingFlags.Static))
);

Alternative way of adding custom condition methods is creating a public static class with a static function and mark the class and method with the attributes [ConditionMethods] and [ConditionMethod] respectively.

You can find a sample implementation of a custom filter here

Then you have to tell NLog where to find your assembly (Ex. NLog.ConditionMethodsAssembly.dll)

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.netfx35.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
    <extensions>
		<add assembly="NLog.ConditionMethodsAssembly" />
    </extensions>
   ...
<nlog>

Examples

Here are several examples with conditions:

<rules>
    <logger name="*" writeTo="file">
        <filters defaultAction="Log">
            <when condition="exception != null" action="Log" />
            <when condition="length(message) > 100" action="Ignore" />
            <when condition="'${OnHasProperties:1}' != ''" action="Ignore" />
            <when condition="logger == 'MyApps.SomeClass'" action="Ignore" />
            <when condition="(level >= LogLevel.Debug and contains(message, 'PleaseDontLogThis')) or level==LogLevel.Warn" action="Ignore" />
            <when condition="not starts-with(message, 'PleaseLogThis')" action="Ignore" />
            <when condition="contains(message, '&quot;Bob&quot;')" action="Ignore" />  <!-- "Bob" -->
        </filters>
    </logger>
</rules>
Clone this wiki locally