Is there a way in Serilog to filter Messages that starts with certain keyword?

3.2k Views Asked by At

I have a project with following Serilog configuration which works perfectly fine in using filter to exclude logs whose SourceContext starts with "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"            
    ]
}

I am looking for something that would filter the logs by certain keyword on message. So instead of using SourceContext, I need to filter logs whose actual Message starts from keyword "AUDIT:".

I tried to filter by using something like following but it did not work.

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

Any idea if we can even achieve something like this?

2

There are 2 best solutions below

0
On BEST ANSWER

In the new library of serilog, @Message is @m

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

Similarly,

Timestamp: @t
Level: @l
MessageTemplate: @mt
Exception: @x
Properties: @p

Hope, this helps!!!

0
On

I found out what the issue was. In case for filtering via Message, we need to put @ infront of Message unlike SourceContext. So the following filter worked:

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