-
Notifications
You must be signed in to change notification settings - Fork 210
Description
Assuming, we'd like to initialize Serilog in the first few lines of Program.Main()
, and independently of ASP.NET Core/other hosting code, how can we support sinks and other pipeline elements that depend on the framework and components that are initialized later?
For example, in #84 there's a discussion regarding the use of Application Insights configuration from dependency injection in a Serilog sink.
LateInitSink
in this gist demonstrates a possible approach:
var signalRSink = new LateInitSink();
Log.Logger = new LoggerConfiguration()
.WriteTo.Sink(signalRSink)
.CreateLogger();
Log.Information("Sadly, nobody will get this");
// ... resolve that hub ...
signalRSink.Init(wt => wt.Console());
Log.Information("Ah so nice to be loggin' again");
@khellang suggested using a name like DependencyInjectedSink
instead of LateInitSink
, so make the API more searchable/discoverable.
We could, finalize/ship an implementation of this approach.
The need to also support enrichers, filters, and so-on, could be met by including a range of similar types for those cases.
As an alternative, or extension of this idea, we could create a wrapper API that mimics LoggerConfiguration
and sets up the full range of extension points for DI (rough sketch):
// Initialize what we can, early on. The `deferred` variable
// will hold a `DeferredLoggerConfiguration` that's hooked
// into late-init sinks, enrichers, etc. by a new `CreateLogger()`
// extension-based overload.
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger(out var deferred);
// Later, post-DI-setup, or elsewhere in the app:
deferred
.AddSink(writeTo => writeTo.File(...))
.AddEnricher(enrich => enrich.WithProperty(...))
.UpdateLogger();
This API should be possible using some extension points already in 2.9.0; it would be nicer to support deferred.WriteTo.File()
etc. but we'd need new APIs to enable it.
Thoughts?
See also #130.