使用日志记录系统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日志?
发布评论