问题
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