gpt4 book ai didi

c# - 如何在参数中为自定义 Enricher 编写正确的 appsettings.json 文件

转载 作者:行者123 更新时间:2023-12-02 20:27:46 26 4
gpt4 key购买 nike

我有一个自定义Enricher:CorrelationIdsEnricher,以便将CorrelationIdRequestId写入日志,并且其构造函数有一个参数:ICorrelationContextProvider 用于传递相关上下文提供程序。

在我的项目中,我通过读取appsettings.json配置文件来配置serilog。这是配置文件:

{
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Common.Logging", "Common.Correlation" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] [{EventId}] [{RequestId} {CorrelationId}] {Message}{NewLine}{Exception}",
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console"
}
}
],
"Enrich": [
"FromLogContext",
{
"Name": "WithCorrelationIds",
"Args": {
"provider": "Correlation.ServerContextProvider::Default, Common.Correlation"
}
}
],
}
}

但是它无法正确设置CorrelationIdsEnricher

有人知道为什么吗?

最佳答案

原因是我忘记添加 WithCorrelationIds 扩展方法。我认为一开始实现 CorrelationIdsEnricher 就足够了。

查看源代码后ConfigurationReader.cs serilog-settings-configuration 中,我发现我忘记实现扩展 WithCorrelationIds

也就是说,为了支持从自定义 EnricherSink 的配置中初始化 serilog,我们不仅需要创建 Enricher > 和 Sink 类,还实现了它们的 LoggerSinkConfiguration 扩展。

附上CorrelationIdsEnricher实现:

using Common.Correlation;
using Serilog.Core;
using Serilog.Events;

namespace Common.Logging.Enrichers
{
public class CorrelationIdsEnricher : ILogEventEnricher
{
private readonly ICorrelationContextProvider _provider;

public CorrelationIdsEnricher(ICorrelationContextProvider provider)
{
_provider = provider;
}

public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
var (requestId, correlationId) = GetIds();
logEvent.AddPropertyIfAbsent(
propertyFactory.CreateProperty("RequestId", requestId, false));
logEvent.AddPropertyIfAbsent(
propertyFactory.CreateProperty("CorrelationId", correlationId, false));
}

private (string requestId, string correlationId) GetIds()
{
var ctx = _provider.Context;
return (ctx?.RequestId ?? string.Empty, ctx?.CorrelationId ?? string.Empty);
}
}
}

LoggerEnrichmentConfiguration扩展:

public static LoggerConfiguration WithCorrelationIds(
this LoggerEnrichmentConfiguration enrichmentConfiguration,
ICorrelationContextProvider provider)
{
return enrichmentConfiguration.With(new CorrelationIdsEnricher(provider));
}

这是一个模拟的关联提供程序:

public class CorrelationContextProvider : ICorrelationContextProvider
{
public static ICorrelationContextProvider Default { get; } = new CorrelationContextProvider();
public ICorrelationContext Context => new CorrelationContext();
}

关于c# - 如何在参数中为自定义 Enricher 编写正确的 appsettings.json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49527808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com