CAD bloke
CAD bloke

Reputation: 8808

How do I write Serilog events to a .NET collection?

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?

Upvotes: 10

Views: 1709

Answers (2)

Reilly Wood
Reilly Wood

Reputation: 2152

I found the following implementations useful as references:

  1. CollectionSink from the Serilog Timings tests
  2. InMemorySink from Serilog.Sinks.InMemory

Upvotes: 4

Nicholas Blumhardt
Nicholas Blumhardt

Reputation: 31842

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.

Upvotes: 9

Related Questions