Wednesday, October 14, 2020

How to show Serilog log in UI

What ? Well I tried to develop simple UI test application by which a tried to manually test my communication classes .

Of course there was idea to show log messages, errors or information messages, in UI, in this case in WPF app . 

But how  ?

So I created a field in UI, lately listBox, but how to fill that field.

Fortunately there is a simple solution , and that is sink "Observers".

_logger = new LoggerConfiguration()
    .WriteTo.Observers(events => events
       .Do(evt => {
           LogTextAppend(Environment.NewLine);
           LogTextAppend(evt.Timestamp.ToString());
           LogTextAppend(": ");
           LogTextAppend(evt.Level.ToString());
           LogTextAppend(": ");
           try
           {
               LogTextAppend(string.Format(evt.MessageTemplate.Text,
                      evt.Properties.ToArray()));
           }
           catch
           {
               LogTextAppend(evt.MessageTemplate.Text);
           }
           LogTextAppend(Environment.NewLine);
           if (!(evt.Exception is null))
           {
               LogTextAppend(JsonConvert.SerializeObject(evt.Exception));
               LogTextAppend(Environment.NewLine);
           }
       })
    .Subscribe())
    .CreateLogger();

Of course it can by simpler or more complicated, but that is up to you.

Just use nuget Serilog.Sinks.Observable