Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map ILogger to Serilog's Logger after ASP.NET Core 2 logging update

From @nblumhardt's post:

You can then go ahead and delete any other logger configuration that’s hanging around: there’s no need for a "Logging" section in appsettings.json, no AddLogging() anywhere, and no configuration through ILoggerFactory in Startup.cs.

I am getting an exception when using Serilog; and ILogger in my controller.

private readonly ILogger _logger;

public CustomersController(ILogger logger)
{
    _logger = logger;
}

Results in:

An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'Customers.Api.Controllers.CustomersController'.

Would I still need to provide some information to DI in the Startup.ConfigureServices() method?

My Program class, to my knowledge, follows instructions in the post.

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.Console()
            .CreateLogger();

        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseSerilog()
            .Build();
}
like image 714
leon Avatar asked Aug 30 '17 07:08

leon


1 Answers

Change expected type from ILogger logger to ILogger<CustomersController> logger:

private readonly ILogger _logger;

public CustomersController(ILogger<CustomersController> logger)
{
    _logger = logger;
}
like image 113
Set Avatar answered Oct 19 '22 09:10

Set