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.
You didn't specify how you are logging exceptions, but assuming you are using something like:
Log.Error("An error occurred: {Exception}", exception);
then the exception will be rendered using ToString(). In that case, couldn't you simply do this instead:
Log.Error("An error occurred: {Exception}", exception.ToString().Replace(System.Environment.NewLine, "\\r\\n"));
Of course, you could refactor this into a method (maybe an extension method) if you need to do it more than one place.
来源:https://stackoverflow.com/questions/49700265/remove-new-lines-from-message-and-exception