I'm trying to attach Serilog to Dotnet core logging framework in a console application. Everything works great in terms of configuration. However, I cannot somehow get the Dependency Injection to work.
For this logging approach that I'm following, each class that needs logging will have to work with ILogger field. The problem that I have is how to register ILogger service as an open-generic type(So I can pass any ILogger<>). When I run my current code I get this exception:
Open generic service type 'Microsoft.Extensions.Logging.ILogger`1[TCategoryName]' requires registering an open generic implementation type. (Parameter 'descriptors')
I have looked at the thread over here but it seems like my problem is a bit different.
This is my code:
The "Test" is a class that needs logging functionality:
public class Test
{
private readonly ILogger _logger;
public Test(ILogger<Test> logger)
{
_logger = logger;
}
public void DoSomething()
{
//code here
_logger.LogInformation("This is the logged error");
}
}
In the Main I have something like:
var log = serviceProvider.GetService<ILogger<Test>>();
new Test(log).DoSomething();
And this is how I configure my ILogger service:
public static IServiceCollection ConfigureSerilog(this IServiceCollection services)
{
var logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning)
.WriteTo.Console(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information)
.WriteTo.File(@"Logs\orgManager.log", rollingInterval: RollingInterval.Day)
.WriteTo.Sink(new TelegramSink(), LogEventLevel.Error)
.CreateLogger();
ApplicationLogging.LoggerFactory.AddSerilog(logger);
services.AddSingleton(typeof(ILogger<>), s => ApplicationLogging.CreateLogger(typeof(ILogger<>)));
return services;
}
This is the ApplocationLogging class(accessible throughout the application):
public static class ApplicationLogging
{
public static ILoggerFactory LoggerFactory { get; } = new LoggerFactory();
public static ILogger CreateLogger(Type t)
{
return LoggerFactory.CreateLogger(t);
}
}