Serilog - 如何自定义格式化文件接收器的解构 Class 对象的输出
Serilog - How to Custom Format the Output of a Destructured Class Object for File Sink
我正在使用 Serilog 登录到两个 'sinks'。
- 滚动文本文件
- 顺序
我想记录一个复杂类型 - FileInfo 对象。
在 Seq 中,我想要完整的对象及其所有可用的属性。
然而在RollingTextFile中,我只想在文本文件中打印'fileInfo.FullName',否则文本文件会很乱并且难以阅读。
我的日志记录语句如下;
logger.Information("Processing File: {@fileInfo} - Attempt ({intAttemptCounter}/3).",fileInfo, intAttemptCounter)
这在解构 fileInfo 对象的情况下按预期工作,但如上所述,生成了一个混乱且不可读的文本文件。
我想我需要使用此处概述的自定义 "Format Provider"; https://github.com/serilog/serilog/wiki/Formatting-Output#format-providers
但我不知道如何为 fileInfo class 对象实现它并将它仅应用于 RollingTextFile 接收器。我也找不到任何其他示例实现。
您可以只在消息中包含名称(将显示在滚动文件中)并将完整信息附加为 属性(将仅显示在 Seq 中)而不是条件格式。
var withFileInfo = logger.ForContext("File", fileInfo, destructureObjects true);
withFileInfo.Information("Processing File: {FileName} - Attempt ({intAttemptCounter}/3).",
fileInfo.FullName, intAttemptCounter)
这也会使 Seq 中的显示效果更好,因为消息将只包含简单的文件名。
(另外,请注意 - withFileInfo
记录器可以在循环的每次迭代中重复使用,因此序列化 fileInfo
的成本只需支付一次。)
我正在使用 Serilog 登录到两个 'sinks'。
- 滚动文本文件
- 顺序
我想记录一个复杂类型 - FileInfo 对象。
在 Seq 中,我想要完整的对象及其所有可用的属性。
然而在RollingTextFile中,我只想在文本文件中打印'fileInfo.FullName',否则文本文件会很乱并且难以阅读。
我的日志记录语句如下;
logger.Information("Processing File: {@fileInfo} - Attempt ({intAttemptCounter}/3).",fileInfo, intAttemptCounter)
这在解构 fileInfo 对象的情况下按预期工作,但如上所述,生成了一个混乱且不可读的文本文件。
我想我需要使用此处概述的自定义 "Format Provider"; https://github.com/serilog/serilog/wiki/Formatting-Output#format-providers
但我不知道如何为 fileInfo class 对象实现它并将它仅应用于 RollingTextFile 接收器。我也找不到任何其他示例实现。
您可以只在消息中包含名称(将显示在滚动文件中)并将完整信息附加为 属性(将仅显示在 Seq 中)而不是条件格式。
var withFileInfo = logger.ForContext("File", fileInfo, destructureObjects true);
withFileInfo.Information("Processing File: {FileName} - Attempt ({intAttemptCounter}/3).",
fileInfo.FullName, intAttemptCounter)
这也会使 Seq 中的显示效果更好,因为消息将只包含简单的文件名。
(另外,请注意 - withFileInfo
记录器可以在循环的每次迭代中重复使用,因此序列化 fileInfo
的成本只需支付一次。)