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

最后都变了- 提交于 2021-02-06 15:31:17

问题


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:


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.



来源:https://stackoverflow.com/questions/35567814/is-it-possible-to-display-serilog-log-in-the-programs-gui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!