Serilog Filters - Configured in C#

257 Views Asked by At

I am attempting to support multiple sinks from a single logger. Sometimes we need to write to a database, other times to file. From what I've read it seems that 'Filters' are the way to go...

I can successfully configure serilog to write logs to my database with custom formatting etc. (I have this working without issue) logConfig.WriteTo.ApplicationDatabase(connectionString).

My challenge is now to write logs to one sink(ApplicationDatabase) or the other(file) depending upon whether the enriched log contains a particular property ['SpecialEvent' (string)] that is not null.

So far I have the following. I get the file created on disk, but it seems that the logs are being written to both the database and the file. Any ideas where I'm going wrong?

                    .WriteTo.Logger(lc => lc
                    .Filter.ByIncludingOnly(le => isSpecialEventPresent(le)));

                    serilogConfig.WriteTo.File(@".\logs\LocalFile.log")
                    .Filter.ByExcluding(le => isSpecialEventPresent(le));

The predicate defined for the filter...

                        LogEventPropertyValue eventVal;
                        if (le.Properties.TryGetValue("SpecialEvent", out eventVal) &&
                                eventVal is ScalarValue &&
                                ((ScalarValue)eventVal).Value != null)
                        {
                            return string.IsNullOrWhiteSpace(eventVal.ToString());
                        }

                        return false;
                    };
0

There are 0 best solutions below