从 Message 和 Exception 中删除新行 [英] Remove new lines from Message and Exception
问题描述
我在 Asp dot net core 应用程序中使用 Serilog.我希望我的日志文件是人类可读的,但也能够很容易地被解析.
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.
我遇到的问题是用换行符记录异常.某些 Microsoft 事件的消息包含新行.
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.
我可以编写自己的 ITextFormatter 实现,用 \r\n 替换新行,但这意味着我需要复制 MessageTemplateTextFormatter 和其他类中的大部分逻辑.
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.
推荐答案
在深入研究了一段时间后,我得出了一个答案.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.
这篇关于从 Message 和 Exception 中删除新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!