Search code examples
serilog

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?


Solution

  • 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.