【问题标题】:Is there a way in Serilog to filter Messages that starts with certain keyword?Serilog 中有没有办法过滤以某个关键字开头的消息?
【发布时间】:2021-09-13 03:54:06
【问题描述】:

我有一个具有以下 Serilog 配置的项目,它在使用过滤器排除 SourceContext 以“Microsoft”开头的日志时工作得很好。

"Serilog": {
    "WriteTo": [           
        {
            "Name": "File",
            "Args": {                    
                "path": "C:\\FE\\Logs\\Gateway\\LOG-.txt",
                "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fffffff}  | {Level:u3} {Message}"                   
            }
        }
    ],
    "Filter": [
        {
            "Name": "ByExcluding",
            "Args": {
                "expression": "StartsWith(SourceContext, 'Microsoft.')"
            }
        }
    ],
    "Enrich": [
        "FromLogContext",
        "WithMachineName"            
    ]
}

我正在寻找可以通过消息中的某个关键字过滤日志的东西。因此,我需要过滤实际消息从关键字“AUDIT:”开始的日志,而不是使用 SourceContext。

我尝试使用以下内容进行过滤,但没有成功。

    "Filter": [
        {
            "Name": "ByIncludingOnly",
            "Args": {
                "expression": "StartsWith(Message, 'AUDIT:')"
            }
        }
    ]

知道我们是否可以实现这样的目标吗?

【问题讨论】:

  • 不起作用是什么意思?你想要 ByIncludingOnly 吗?
  • 对不起,我打错了。即使使用 "ByIncludingOnly" ,它也不是用 "expression" 过滤的:"StartsWith(Message, 'Application')" 我的问题是我们不能像使用 "SourceContext" 那样使用 "Message" 进行过滤吗?

标签: .net logging serilog serilog-filter


【解决方案1】:

我发现了问题所在。如果通过 Message 进行过滤,我们需要将 @ 放在 Message 的前面,这与 SourceContext 不同。所以下面的过滤器起作用了:

     "Filter": [
            {
              "Name": "ByExcluding",
              "Args": {
                "expression": "StartsWith(@Message, 'AUDIT::')"
              }
            }
          ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 2021-12-18
    相关资源
    最近更新 更多