且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 Message 和 Exception 中删除新行

更新时间:2023-12-03 21:39:34

在深入研究了一段时间后,我得出了一个答案.Andy West 的回答为我指明了正确的方向.

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.

这里有两个独立的问题:消息中的 CRLF 和异常中的 CRLF.

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

通过将 outputTemplate 中的{Message}"更改为{Message:j}",我能够解决消息问题.

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);
    }        
}

这添加了一个名为 EscapedException 的新属性.必须使用 .Enrich.With() 将其添加到配置中.

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

然后我在 outputTemplate 中用{EscapedException}"替换了{Exception}".

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