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