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

leon picture leon · Aug 30, 2017 · Viewed 16.7k times · Source

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();
}

Answer

Set picture Set · Aug 30, 2017

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

private readonly ILogger _logger;

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