是否可以在程序的GUI中显示Serilog日志?

编程入门 行业动态 更新时间:2024-10-09 20:23:44
本文介绍了是否可以在程序的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日志?

本文发布于:2023-11-15 19:43:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1597406.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:程序   日志   GUI   Serilog

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!