简体   繁体   中英

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

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

You can install Serilog as the logger under the Microsoft logging framework by including the Serilog.Extensions.Logging package and including the following in your app startup:-

public void ConfigureServices(IServiceCollection services)
{
    services.AddLogging(x =>
    {
        x.ClearProviders();
        x.AddSerilog(dispose: true);
    });

    ...

Or, as an alternative to injecting, if you just want a reference to the Serilog logger, Serilog.Log has a static method Log to create a logger...

...
using Serilog;
...

namespace Test.Controllers
{
    public class TestController : Controller
    {
        private readonly static ILogger log = Log.ForContext(typeof(TestController));

        public TestController()
        {
            log.Debug("Test");
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM