.Net 中的 Serilog:通过 appSettings.json 添加自定义丰富器不起作用

Dek*_*iri 4 .net c# serilog .net-core

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

我完全按照书本,遵循文档。我还遵循了这样的非官方介绍https://www.ctrlaltdan.com/2018/08/14/custom-serilog-enrichers/

上面的介绍适用于金块丰富器(如 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>();
    }
}
Run Code Online (Sandbox Code Playgroud)

和设置:

在此输入图像描述

我会注意到,在代码中添加我的增强器工作正常。有什么建议吗?

pfx*_*pfx 7

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

Serilog 文档中

使用部分包含配置方法(WriteTo.File()、Enrich.WithThreadId())所在的程序集列表。

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

"Using": [ "Example.Assembly.Name" ]
Run Code Online (Sandbox Code Playgroud)