All the examples I can find about using Serilog in an ASP .NET Core Web Application use Microsoft's ILogger<T>
interface instead of using Serilog's ILogger
interface.
How do I make it so that Serilog's ILogger can be injected via constructor, instead?
using Serilog;
public class HomeController : Controller
{
ILogger logger;
public HomeController(ILogger logger)
{
this.logger = logger;
}
public IActionResult Index()
{
this.logger.Information("Index was called");
return View();
}
}
NET 6 as a logging provider. Let's set up Serilog as Logging Provider in the native logging system in . NET so you can use the Microsoft ILogger interface.
Installing Serilog is simple. First, we open the NuGet Package Manager and search for the Serilog. AspNetCore package and install the latest stable version. After a few seconds, Serilog is installed.
The ILoggerFactory is the factory interface for creating an appropriate ILogger type instance and also for adding the ILoggerProvider instance. public interface ILoggerFactory : IDisposable { ILogger CreateLogger(string categoryName); void AddProvider(ILoggerProvider provider); }
If you prefer ILogger
instead of ILogger<HomeController>
, you could try to register ILogger
.
Here are two options to use Serialog.Information
.
Use Log.Logger
Log.Logger.Information("Information Log from Log.Logger");
Register ILogger
//Startup.cs
services.AddSingleton(Log.Logger);
//Use
public class HomeController : Controller
{
private readonly ILogger _logger;
public HomeController(ILogger logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.Information("Inform ILog from ILogger");
return View();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With