Remove new lines from Message and Exception

ぐ巨炮叔叔 提交于 2019-12-06 08:27:08

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.

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