【问题标题】:Serilog in .Net: Adding custom enricher via appSettings.json doesn't work.Net 中的 Serilog:通过 appSettings.json 添加自定义浓缩器不起作用
【发布时间】:2021-08-20 14:42:37
【问题描述】:

使用 serilog,我试图通过 appSettings.json 添加我自己的自定义浓缩器,但没有成功。

我完全按照书本,按照文档进行。 我也跟着这样的非官方介绍https://www.ctrlaltdan.com/2018/08/14/custom-serilog-enrichers/

上面的介绍适用于 nuggets 丰富器(如 Serilog.Enrichers.Environment、Serilog.Enrichers.Thread 等) 但不适用于我的自定义浓缩器。 以下是相关代码:

public class ClassNameEnricher: ILogEventEnricher
{
    private string GetClassName()
    {
        StackTrace trace = new StackTrace();
        bool foundFrame = false;
        int currentFrame = 0;
        while (!foundFrame)
        {
            if (trace.GetFrame(currentFrame).GetMethod().ReflectedType.FullName == typeof(Logger).FullName)
            {
                foundFrame = true;
            }

            currentFrame++;
        }

        return trace.GetFrame(currentFrame).GetMethod().ReflectedType.FullName;
    }

    public virtual void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        LogEventProperty className = propertyFactory.CreateProperty("ClassName", GetClassName());
        logEvent.AddPropertyIfAbsent(className);
    }
}


public static class LoggerEnrichmentConfigurationExtensions
{
    public static LoggerConfiguration WithClassName(this LoggerEnrichmentConfiguration enrich)
    {
        return enrich.With<ClassNameEnricher>();
    }
}

和设置:

我会注意到在代码中添加我的 enrihcer 可以正常工作。 有什么建议吗?

【问题讨论】:

    标签: c# .net .net-core serilog


    【解决方案1】:

    您必须在 "Using" 部分中包含程序集的名称。

    来自Serilogdocumentation

    Using 部分包含配置的程序集列表 方法(WriteTo.File()、Enrich.WithThreadId())驻留。

    请注意,您所指的那篇文章中存在程序集配置:

    "Using": [ "Example.Assembly.Name" ]
    

    【讨论】:

      猜你喜欢
      • 2022-07-07
      • 2015-10-25
      • 1970-01-01
      • 2022-11-09
      • 2016-01-01
      • 2019-01-14
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      相关资源
      最近更新 更多