Map ILogger to Serilog's Logger after ASP.NET Core 2 logging update
Solution 1
Change expected type from ILogger logger
to ILogger<CustomersController>
logger:
private readonly ILogger _logger;
public CustomersController(ILogger<CustomersController> logger)
{
_logger = logger;
}
Solution 2
Another alternative, if you still wish to use Serilog's own ILogger
rather than ASP.NET Core's ILogger<T>
, is to register the Serilog logger with your IoC container.
There's an integration for Autofac that does this at https://github.com/nblumhardt/autofac-serilog-integration, other containers may have integration packages out there, too.
Related videos on Youtube
Comments
-
leon almost 2 years
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;
andILogger
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(); }
-
leon over 6 yearsThanks. I reset my edits to test this and it worked. Do we know why? :-)
-
Set over 6 years