5

Using serilog, I'm trying to add custom enricher of my own via appSettings.json without success.

I went exactly by the book, following the documentation. I also followed non official introduction like this https://www.ctrlaltdan.com/2018/08/14/custom-serilog-enrichers/

The introduction above work fine with nuggets enrichers (like Serilog.Enrichers.Environment, Serilog.Enrichers.Thread and so on) but doesn't work with my custom enricher. Here is the relevant code:

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

and the settings:

enter image description here

I'll note that adding my enrihcer in code working fine. Any suggestion?

1 Answer 1

11

You have to include the name of your assembly in the "Using" section.

From the Serilog documentation

Using section contains list of assemblies in which configuration methods (WriteTo.File(), Enrich.WithThreadId()) reside.

Notice in that article you are referring to, that assembly configuration is present:

"Using": [ "Example.Assembly.Name" ]
Sign up to request clarification or add additional context in comments.

2 Comments

This hasn't worked for me. I've added the assembly (The web project itself) to the Using but it just gets ignored and isn't being added to the Enrichers collection in the logger.
@KeithJackson Make sure to use the name of the extension method not the class name in the "Enrichers" array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.