When building up programmatically a LoggerConfiguration
to be used later, I wanted and succeeded to constrain the using of an enricher for all source context values except one (Global.asax from an old webforms website).
But it seems to me like this moves away (I don't like that Invoke
call) from what I think the Serilog library intended as practice through it's quite nice and elegant fluent API:
private static LoggerConfiguration GetBasicLoggerConfig()
{
return new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.When(
logEvent => !Matching.FromSource("ASP.global_asax").Invoke(logEvent),
enrichmentConfig => enrichmentConfig.WithAnyKindOfEnricher());
}
I use this logic to exclude a list of enrichers from running when out of context and only want them to execute when inside the page's lifecycle. But regardless of this case, as I'm going to apply this approach in other places, I want to keep it clean&short and I am mostly interested in the concept itself - "enrich by excluding a particular context".
I have looked for ways like WhenNot
or NotMatching
to express "negation" / "exclusion" and didn't manage to find them in the library. Tried with other methods offered by the static class Matching
but to no avail. The project is big and I'd like to personalize the whole logging depending on various contexts (so ending up using a series of Enrich.When()
s - and with a big list of enrichers, obtaining the complete config tree with several "exclude only one context" parts seems ugly/messy).
Of course, centrally declaring a default value for context as in the example below does not cut it because there will be different contexts declared through .ForContext<T>()
and all of them but one must be "catched" in the condition for enriching.
// this does not cut it
return new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.WithProperty(Serilog.Core.Constants.SourceContextPropertyName, "default")
.Enrich.When(Matching.FromSource("default"),
enrichmentConfig => enrichmentConfig.WithAnyKindOfEnricher());
Hope that I managed to explain what I'm trying to achieve. (The lambda parameter names are long for clarity reasons)
So, did I miss something or is there another approach? How to best achieve this "enriching by exclusion"?
later edits:
- Forgot to mention that I log only to files (using file sink).
- Not looking to integrate Seq (I know about its advantages), at least not in the near future.
Serilog.Filters.Expressions is nicer for this:
// dotnet add package serilog.filters.expressions
.Enrich.When(
"SourceContext <> 'ASP.global_asax'"),
enrichmentConfig => enrichmentConfig.WithAnyKindOfEnricher());