.netloggingserilogserilog-filter

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


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?


Solution

  • 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!!!