There is an answer here: How do I pass a dependency to a Serilog Enricher? which explains you can pass an instance in.
However to do that I would need to move my logger setup after my dependency injection code has ran (in the startup.cs
)
This means that startup errors won't be logged because the logger won't be ready yet.
Is there a way to somehow configure serilog to run in my Main()
method, but also enrich data with a DI item? The DI item has further dependencies (mainly on database connection) although it is a singleton.
I've googled this and read something about adding things to a context, but I've been unable to find a complete working example that I can adapt.
Most of the examples I've found involve putting code into the controller to attach information, but I want this to be globally available for every single log entry.
My Main starts with :
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elasticUri))
{
AutoRegisterTemplate = true,
})
.CreateLogger();
Before going into the .NET Core MVC code
CreateWebHostBuilder(args).Build().Run();
My DI object is basically a "UserData" class that contains username, companyid, etc. which are properties that hit the database when accessed to get the values based on some current identity (hasn't been implemented yet). It's registered as a singleton by my DI.