Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

serilog

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?

like image 441
CAD bloke Avatar asked Mar 31 '16 08:03

CAD bloke


Video Answer


1 Answers

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.

like image 139
Nicholas Blumhardt Avatar answered Oct 11 '22 20:10

Nicholas Blumhardt