在Serilog中,当使用{Properties}格式说明符时,如何从JSON格式的日志消息中删除空括号?

4sup72z8  于 2023-04-22  发布在  其他
关注(0)|答案(2)|浏览(122)

下面是outputTemplate字符串:

var formatString = "{NewLine}[{Timestamp:dd-MMM-yyyy HH:mm:ss}] {Level} {SourceContext}{NewLine}{Properties:j}{NewLine}{Message:lj}{NewLine}{Exception}";

我配置了几个丰富器来添加和删除属性。在没有要记录的属性的情况下,我会在一行上得到空的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.

但是,在没有属性的情况下,我得到了这个

[05-Jul-2019 07:13:57] Information Microsoft.AspNetCore.Mvc
{}
This is some log message that contains no properties

空的JSON括号{}在我的日志中到处都是,只是增加了噪音。我如何扩展或重写Serilog来摆脱这些括号?

vnjpjtjt

vnjpjtjt1#

你可以使用这个serilog扩展:
dotnet add package Serilog.Expressions
参见github serilog-expressions:条件块:你可以像... {#if Property is not null} ({Property}){#end} ...这样做

2nbm6dog

2nbm6dog2#

感谢@Kraego,我终于弄明白了这一点。下面是如何使用Serilog.Expressions NuGet包设置日志记录器:

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

在我的例子中,我只想在异常的情况下打印属性(@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);

以及它们相应的输出:

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>

相关问题