是否可以在程序的GUI中显示Serilog日志? [英] Is it possible to display Serilog log in the program's GUI?

查看:50
本文介绍了是否可以在程序的GUI中显示Serilog日志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用日志记录系统Serilog可以在文本框,列表视图或其他GUI控件中显示日志;有什么机制可以实现这一目标?

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?

推荐答案

Serilog为此提供了 ILogEventSink 扩展点.您可以使用它将日志事件添加到列表中,或将它们呈现到某个地方的 TextWriter 上.

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.

根据您的需要,可能会有不同程度的复杂程度.这个(基于 ConsoleSink )应该可以帮助您:

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();

然后,由您的应用决定如何在显示时将 sink.Events 加载到文本框中.

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

添加一些代码以限制 Emit()中的队列大小是一个好主意.

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

这篇关于是否可以在程序的GUI中显示Serilog日志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆