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 Sinks In the packages that we are going to install to our ASP.NET Core application, Sinks for Console and File are included out of the box. That means we can write logs to Console and File System without adding any extra packages. Serilog supports various other destinations like MSSQL,SQLite, SEQ and more.
Serilog is an easy-to-set-up logging library for . NET with a clear API. In the long list of the Serilog's features you can find: Support of structured logging, which allows logs to be treated as data sets rather than text. Compatibility with asynchronous applications and systems.
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.
You might want to check out Serilog.Sinks.RichTextBox
sink which can write logs to a RichTextBox
control with colors, formatting, etc. similar to what you'd expect in a Console application (you have full control of the colors through themes).
The sink was originally built for WPF applications, but can easily be used with Windows Forms application as well and there's an example in the repository that shows how to use it with Windows Forms.
Disclaimer: I'm the author of the Serilog.Sinks.RichTextBox
sink.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With