[英]How to write the right appsettings.json file for custom Enricher within argument
我有一個自定義的Enricher: CorrelationIdsEnricher
,以便將CorrelationId
和RequestId
寫入日志,其構造函數具有一個參數: ICorrelationContextProvider
用於傳遞相關上下文提供程序。
在我的項目中,我通過閱讀appsettings.json
配置文件appsettings.json
配置appsettings.json
。 這是配置文件:
{
"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
就足夠了。
在查看serilog-settings-configuration
的源代碼ConfigurationReader.cs之后,我發現我忘記實現擴展WithCorrelationIds
。
這就是說,為了支持從配置初始化serilog為我們定制Enricher
和Sink
,我們需要不僅創造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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.