Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a dependency to a Serilog Enricher?

I'm using Serilog in my application for logging. When I'm configuring the logger, I have code like this:

var log = new LoggerConfiguration()
    .Enrich.With<MySerilogEnricher>()
    .ReadAppSettings()
    .CreateLogger();

I want to inject some dependencies into my MySerilogEnricher class, but when I try, I get this compiler error:

error CS0310: 'SerilogEnricher' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TEnricher' in the generic type or method 'LoggerEnrichmentConfiguration.With()'

I understand why I'm getting this error, but I don't see an easy way around it. Ideally, there'd be a WithInstance call that I could use like this:

var instance = new MySerilogEnricher(myDependency);
var log = new LoggerConfiguration()
    .Enrich.WithInstance<MySerilogEnricher>(instance)
    .ReadAppSettings()
    .CreateLogger();

Is there any way to pass a dependency to MySerilogEnricher? I could maybe have a class with MySerilogEnricher in it and pass the dependency to it in a property, but that seems messy.

like image 520
user2023861 Avatar asked Oct 03 '16 18:10

user2023861


1 Answers

You can use the .With() method without the generic to pass an instance of your enricher. So in your example, it would be:

var instance = new MySerilogEnricher(myDependency);
var log = new LoggerConfiguration()
    .Enrich.With(instance)
    .ReadAppSettings()
    .CreateLogger();
like image 80
rmc00 Avatar answered Oct 30 '22 00:10

rmc00