Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to display Serilog log in the program's GUI?

Tags:

c#

.net

serilog

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?

like image 255
TheColonel26 Avatar asked Feb 23 '16 02:02

TheColonel26


People also ask

How does Serilog work in net core?

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.

What is Serilog?

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.


2 Answers

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.

like image 51
Nicholas Blumhardt Avatar answered Sep 19 '22 20:09

Nicholas Blumhardt


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).

Serilog.Sinks.RichTextBox

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.

like image 20
C. Augusto Proiete Avatar answered Sep 18 '22 20:09

C. Augusto Proiete