pampua84
pampua84

Reputation: 884

C# Serilog filter by log object type or property

I have a question about how to filter the log on the $type field or by property in the log, I am trying all ways but to no avail. This is the log I have:

{
    "@t": "2021-03-25T14:20:27.0883534Z",
    "@mt": "{@UserEvent}",
    "UserEvent": {
        "Email": "[email protected]",
        "ClientId": null,
        "Endpoint": "UI",
        "Name": "J.Thunders",
        "SubjectId": "6c321d61-2e4b-4953-b6de-a1fddb80ab50",
        "Provider": null,
        "MachineName": "MyMachine",
        "Category": "Authentication",
        "EventType": "Success",
        "Id": 1000,
        "Message": null,
        "ActivityId": "0HM7FJ4CUF78K:00000023",
        "TimeStamp": "2021-03-25T14:20:24.0000000Z",
        "ProcessId": 25684,
        "LocalIpAddress": "127.0.0.1:5002",
        "RemoteIpAddress": "127.0.0.1",
        "$type": "UserLoginSuccessEvent"
    }
}

I tried with the following configuration, but nothing:

Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .WriteTo.Logger(cfg => cfg.Filter.ByIncludingOnly("type like '%User%'").WriteTo.File(new CompactJsonFormatter(),
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs/log-.log"),
                LogEventLevel.Verbose,
                rollingInterval: RollingInterval.Day))
            .CreateLogger();

or

cfg.Filter.ByIncludingOnly("@p['UserEvent']")

but neither works. Instead if i use filter by code like this:

cfg.Filter.ByIncludingOnly(Matching.WithProperty("UserEvent")

it works. How can I do to get this filter, can I filter it based on the TypeOf?
The only thing not to write the expression of the filter through code (linq etc.), why then do I have to bring it back into the app settings?
Thanks

Upvotes: 0

Views: 3308

Answers (1)

Nicholas Blumhardt
Nicholas Blumhardt

Reputation: 31832

Assuming you are using Serilog.Expressions for the filtering, this line is close:

Filter.ByIncludingOnly("type like '%User%'")

To get to the $type of the UserEvent property, you need TagOf():

Filter.ByIncludingOnly("TagOf(UserEvent) like '%User%'")

Upvotes: 1

Related Questions