Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove new lines from Message and Exception

Tags:

serilog

I am using Serilog in an Asp dot net core application. I want my my log files to be human readable, but also be able to be parsed easily.

The problem that I have come across is that exceptions are logged with line breaks. Some Microsoft events have messages that include new lines.

I would like to be able to parse the log file with one event per line.

I could write my own implementation of ITextFormatter that replaces new lines with \r\n, but that we mean I would need to duplicate much of the logic in MessageTemplateTextFormatter and other classes.

like image 858
Andrew Radford Avatar asked Oct 16 '22 20:10

Andrew Radford


1 Answers

After digging into this for a while, I was able to come up with an answer. Andy West's answer pointed me in the right direction.

There are two separate issues here: CRLFs in the message and CRLFs in the exception.

I was able to solve the message problem by changing "{Message}" to "{Message:j}" in the outputTemplate.

Changing the exception was a little trickier. I had to add an enricher:

class ExceptionEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        if (logEvent.Exception == null)
            return;

        var logEventProperty = propertyFactory.CreateProperty("EscapedException", logEvent.Exception.ToString().Replace("\r\n", "\\r\\n"));
        logEvent.AddPropertyIfAbsent(logEventProperty);
    }        
}

This adds and new property called EscapedException. This has to be added to the configuration with .Enrich.With().

Then I replaced "{Exception}" with "{EscapedException}" in the outputTemplate.

like image 63
Andrew Radford Avatar answered Oct 21 '22 09:10

Andrew Radford