Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Serilog's ILogger interface in ASP .NET Core Web API Controller

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();
    }
}
like image 666
Lindsey1986 Avatar asked Jul 30 '19 13:07

Lindsey1986


People also ask

Does Serilog use ILogger?

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.

How is Serilog implemented in .NET Core?

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.

What is .NET Core ILogger?

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


1 Answers

If you prefer ILogger instead of ILogger<HomeController>, you could try to register ILogger.

Here are two options to use Serialog.Information.

  1. Use Log.Logger

    Log.Logger.Information("Information Log from Log.Logger");
    
  2. 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();
        }        
    }
    
like image 142
Edward Avatar answered Nov 03 '22 00:11

Edward