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 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 Events { get; } = new ConcurrentQueue();
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.