I am converting a .NET Standard utility library from console logging to ILogger
logging.
The library consists static utility classes, and I am exposing a static ILogger
property to be set by users, to point to whatever logging system they want to use.
I want my .NET Core 3.1 and .NET 5 console apps to use Serilog for logging, and assign the library ILogger
to Serilog, with all the goodness that comes with Serilog.
I am not using DI in the utility library, as it is static methods, not "service" classes.
How do I manually (not using DI) create a Microsoft.Extensions.Logging.ILogger
from a Serilog.ILogger
or a Serilog.Extensions.Logging.SerilogLoggerFactory
.
Any suggestions on an easier way vs. the example code?
// How to create a "Microsoft.Extensions.Logging.ILogger" from a "Serilog.ILogger"?
Microsoft.Extensions.Logging.ILogger logger = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
// https://github.com/serilog/serilog-extensions-logging/blob/dev/samples/Sample/Program.cs
LoggerProviderCollection providerCollection = new LoggerProviderCollection();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.Providers(providerCollection)
.CreateLogger();
ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(providerCollection);
serviceCollection.AddSingleton<ILoggerFactory>(sc =>
{
LoggerProviderCollection loggerProviderCollection = sc.GetService<LoggerProviderCollection>();
SerilogLoggerFactory serilogLoggerFactory = new SerilogLoggerFactory(null, true, loggerProviderCollection);
foreach (ILoggerProvider loggerProvider in sc.GetServices<ILoggerProvider>())
serilogLoggerFactory.AddProvider(loggerProvider);
return serilogLoggerFactory;
});
serviceCollection.AddLogging(logging => logging.AddConsole());
ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
ILogger<Program> programLogger = serviceProvider.GetRequiredService<ILogger<Program>>();
logger = programLogger;
logger.LogInformation("Testing testing");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…