Is it possible to display Serilog log in the program's GUI?

后端 未结 1 1710
野趣味
野趣味 2021-02-13 17:03

With the logging system Serilog is it possible to display the log in a text box, or a list view or some other GUI control; what is the mechanism to get it there?

相关标签:
1条回答
  • 2021-02-13 17:41

    Serilog provides the ILogEventSink extension point for this. You can use it to add log events to a list, or render them onto a TextWriter somewhere.

    There are varying degrees of sophistication possible, depending on your needs. This one (based on ConsoleSink) should get you going:

    class InMemorySink : ILogEventSink
    {
        readonly ITextFormatter _textFormatter = new MessageTemplateTextFormatter("{Timestamp} [{Level}] {Message}{Exception}");
    
        public ConcurrentQueue<string> Events { get; } = new ConcurrentQueue<string>();
    
        public void Emit(LogEvent logEvent)
        {
            if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
            var renderSpace = new StringWriter();
            _textFormatter.Format(logEvent, renderSpace);
            Events.Enqueue(renderSpace.ToString());
        }
    }
    

    Then hooking it up means creating an instance:

    var sink = new InMemorySink();
    Log.Logger = new LoggerConfiguration()
        .WriteTo.Sink(sink)
        .CreateLogger();
    

    Then, it's up to your app to figure out how to load sink.Events into the text box when it is shown.

    Adding some code to limit the size of the queue in Emit() is a good idea.

    0 讨论(0)
提交回复
热议问题