如何使用 C# 在 NLog 中使用条件进行过滤

How to filter using a condition in NLog with C#

我在使用 C# 创建 NLog 目标过滤器时遇到问题。我正在尝试创建一个过滤器来记录到两个不同的目标。我有一个基于包含匹配字符串的消息内容的条件。问题是我似乎无法获得使用机器名或事件上下文内容的条件。

这将通过使用消息本身按预期工作:

var newRule = new LoggingRule("*", logLevel, someWrapper);
newRule.DefaultFilterResult = FilterResult.Ignore;
newRule.Filters.Add(new ConditionBasedFilter()
{
    Condition = "contains(message, 'string')",
    Action = FilterResult.Log
});
config.LoggingRules.Add(newRule);

这些不起作用:

Condition = "contains(machinename, 'string')"
Condition = "equals(machinename, 'string')"
Condition = "machinename == 'string')"
Condition = "contains(event-context:item=SomeItem, 'string')"
Condition = "equals(event-context:item=SomeItem, 'string')"
Condition = "event-context:item=SomeItem == 'string')"

我将看到的上述错误是:

"Unexpected token: ==" OR "Unexpected toekn: ,"

不知道是不是格式不对?我已经尝试了几种不同的选项,但我似乎无法让条件过滤器与机器名或更具体地说是事件上下文一起工作。

感谢您的宝贵时间和帮助!

你的条件缺少的是它周围的一些单引号。

var stringToCompare = "sometext";
var stringCondition = "'${machinename}' == '" + stringToCompare + "'";

...

newRule.Filters.Add(new ConditionBasedFilter()
{
    Condition = stringCondition,
    Action = FilterResult.Log
});

在某些情况下您可以使用布局渲染器,但您需要 ${...} 语法,

所以这会起作用:

Condition = "contains(${machinename}, 'string')"
Condition = "equals(${machinename}, 'string')"
Condition = "${machinename} == 'string'"
Condition = "contains(${event-context:item=SomeItem}, 'string')"
Condition = "equals(${event-context:item=SomeItem}, 'string')"
Condition = "${event-context:item=SomeItem} == 'string'"

另见 docs of the conditions in NLog

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 '<' (<) 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.

可以在此处找到所有可能的布局渲染器 https://nlog-project.org/config(选项卡 'layout-renderers')

可以在此处找到有关如何在 NLog 中进行过滤的官方文档:https://github.com/NLog/NLog/wiki/Filtering-log-messages

NLog 4.6.7 引入了以 lambda 作为输入参数的新 NLog.Filters.WhenMethodFilter

如果您想在不使用 NLog LayoutRenderers 的情况下进行过滤。另见:https://github.com/NLog/NLog/wiki/Filtering-log-messages