Remove new lines from Message and Exception

你。 提交于 2019-12-07 22:55:29

问题


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.


回答1:


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.




回答2:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!