A wrapper for other Serilog sinks. Matches when message has already been logged. Useful if having an aggressive logger, and wants to throttle the output.
Install from NuGet:
Install-Package Serilog.Extensions.WhenRepeated
// At this example duplicated messages are written as as dot
...
private static readonly MessageTemplate RepeatedMessageTemplate = new MessageTemplate(new MessageTemplateParser().Parse(".").Tokens);
new LoggerConfiguration()
.Enrich.WithRepeatedMessagesCount("repeatCount")
.WriteTo
.WhenRepeated(
configureWrappedSink: x => x.Async(y => y.File("/path/to/log.txt")),
options: new WhenRepeatedOptions(
onRepeat: (current, previous) =>
{
return new LogEvent(
timestamp: current.Timestamp,
level: current.Level,
exception: null,
messageTemplate: RepeatedMessageTemplate,
properties: Array.Empty<LogEventProperty>());
})).CreateLogger();
...
The WhenRepeatedOptions type constructor exposes the following members.
Name | Description |
---|---|
onRepeat | Action to be taken when filter matches. |
compare | Statement of that how to compare current log with previous log event. |
timeout | Duration after which message if duplicated will be logged. |
firstStrategy | Strategy that determines how to handle first (not duplicated) log event. |
Enrich Serilog events with repeated messages count property.
...
new LoggerConfiguration()
.Enrich.WithRepeatedMessagesCount("repeatCount") // Set name under which property will be available
.WriteTo
.WhenRepeated(
configureWrappedSink: x => x.Async(y => y.File("/path/to/log.txt")),
options: new WhenRepeatedOptions() // Default options, needed to enable counting. By default increment repeated messages count when same message occurs in 10 seconds time interval.
).CreateLogger();
...
logger.Information(messageTemplate: "{repeatCount}");