I'm using the .NET Core 2.1 HostBuilder class to set up and run a GRPC server and am having trouble getting SeriLog properly configured so that it is used by the .NET Core logging pipeline as well as available (via dependency injection) elsewhere in my app.
class Program
{
private static async Task Main(string[] args)
{
var hostBuilder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddSingleton<ILogger>(BuildLogger);
// other services here
})
.ConfigureLogging((hostContext, loggingBuilder) =>
loggingBuilder.AddSerilog(dispose: true));
await hostBuilder.RunConsoleAsync();
}
private static ILogger BuildLogger(IServiceProvider provider)
{
// create a (global) logger
Log.Logger = new LoggerConfiguration()
...
.CreateLogger();
return Log.Logger;
}
}
The problem is that I need the call to loggingBuilder.AddSerilog()
to use the singleton ILogger
that was registered with the DI services configuration a few lines above.
I realize I could directly call BuildLogger()
to get the ILogger
instance and register that instance with the DI service configuration, but it seems like I shouldn't have to. What I'm looking for is a way, from within the .ConfigureLogging()
method to access a ServiceProvider
instance so I can get the registered ILogger
maybe like
serviceProvider.GetRequiredService<ILogger>();
and pass that to the AddSerilog()
call. Any ideas?
ILogger<T>
is part of Microsoft.Extensions.Logging, not SeriLog. – ChampignonSeriLog.ILogger
... – Champignon