10

I want to write Serilog Warning events to a .NET collection so they can be included in a report to the user. How do I configure the static Log.Logger to write to something like a static List<string<> ?

I saw the Rx Observer in the list of provided sinks, this was the only one that seemed to readily make .NET objects available or is there an obvious alternative that I missed?

Alternatively, is this a dumb way to do it - is there a better way to collect just Warning events to massage into a user-facing report?

CAD bloke
  • 8,578
  • 7
  • 65
  • 114

2 Answers2

8
class CollectionSink : ILogEventSink {
    public ICollection<LogEvent> Events { get; } = new ConcurrentBag<LogEvent>();

    public void Emit(LogEvent le) {
        Events.Add(le);
    }
}

var col = new CollectionSink();
Log.Logger = new LoggerConfiguration()
    .WriteTo.Sink(col, LogEventLevel.Warning)
    .CreateLogger();

// read col.Events....

Not sure this one will typecheck but this is essentially how I've done it a few times.

Nicholas Blumhardt
  • 30,271
  • 4
  • 90
  • 101
4

I found the following implementations useful as references:

  1. CollectionSink from the Serilog Timings tests
  2. InMemorySink from Serilog.Sinks.InMemory
Reilly Wood
  • 1,753
  • 2
  • 12
  • 17