Rob*_*b L 11 json serilog asp.net-core
我有以下outputTemplate字符串:
var formatString = "{NewLine}[{Timestamp:dd-MMM-yyyy HH:mm:ss}] {Level} {SourceContext}{NewLine}{Properties:j}{NewLine}{Message:lj}{NewLine}{Exception}";
Run Code Online (Sandbox Code Playgroud)
我有几个丰富的配置来添加和删除属性。在没有要记录的属性的情况下,我一直在一行中获取空的 JSON 括号。例如,当有要记录的属性时,我会收到如下日志消息:
[05-Jul-2019 07:13:57] Information Microsoft.AspNetCore.Mvc
{ "UserName": "SomeUser" }
This is some log message with a property that was not removed by any of the enrichers.
Run Code Online (Sandbox Code Playgroud)
但是,在没有属性的情况下,我会得到这个
[05-Jul-2019 07:13:57] Information Microsoft.AspNetCore.Mvc
{}
This is some log message that contains no properties
Run Code Online (Sandbox Code Playgroud)
空的 JSON 括号{}散落在我的日志中,只是增加了噪音。如何扩展或覆盖 Serilog 以摆脱这些括号?
感谢@Kraego,我终于弄清楚了这一点。以下是使用 NuGet 包设置记录器的方法Serilog.Expressions:
var logger = new LoggerConfiguration()
.WriteTo.Console(
new ExpressionTemplate(
"{@t:yyyy-MM-dd HH:mm:ss.fff} [{@l}] {#if SourceContext is not null} ({SourceContext}){#end}\n{@m}{#if @x is not null}\n{@p}{#end}\n{@x}\n",
theme: TemplateTheme.Literate))
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
就我而言,我只想@p在异常情况下打印属性 ( ),否则我只想要呈现的消息。使用示例:
logger.LogDebug("Sending {Count} records to Kafka broker for asset {AssetId}, session: {SessionId}", 1000, 1234, 5678);
logger.LogWarning(exception, "An Exception was thrown during the processing of Data Source: {DataSource}. Retry attempt {Retry}/{MaxRetries}", "MyFileName.gz", 1, 3);
Run Code Online (Sandbox Code Playgroud)
及其相应的输出:
2023-04-13 05:34:38.543 [Debug] [MyNamespace.Pipeline.Kafka.KafkaMessagePublisher]
Sending 1000 records to Kafka broker for asset 1234, session: 5678
2023-04-13 05:34:39.666 [Warning] [MyNamespace.Importer.Core.Processors.ProcessorPipeline]
An Exception was thrown during the processing of Data Source: MyFileName.gz. Retry attempt 1/3
<CUSTOM EXCEPTION PROPERTIES>
<STACK TRACE>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
257 次 |
| 最近记录: |