Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving error - Unable to resolve service for type 'Serilog.ILogger'

I am trying to implement SeriLog in ASP.NET core application (.NET framework)

Below are steps I performed so far-

1) Added below references in Project.json

"Serilog": "2.2.0",
"Serilog.Extensions.Logging": "1.2.0",
"Serilog.Sinks.RollingFile": "2.0.0",
"Serilog.Sinks.File": "3.0.0"

2) Added following lines to the constructor of your Startup class-

Log.Logger = new LoggerConfiguration()
           .MinimumLevel.Debug()
           .WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "log-{Date}.txt"))
           .CreateLogger();

3) Added following line to the configure method of your Startup class-

loggerFactory.AddSerilog();

4) Injecting the logger to HomeController like this-

ILogger logger;

    public HomeController(ILogger logger)
    {
        this.logger = logger;
    }

5) In About action, trying to log exception like this-

public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";

        try
        {
            throw new Exception("Serilog Testing");
        }
        catch (System.Exception ex)
        {
            this.logger.Error(ex.Message);
        }

        return View();
    }

On running my application, I am getting below error-

System.InvalidOperationException: Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'AspNetCore_SeriLog_trial1.Controllers.HomeController'. at Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] ) at Microsoft.AspNetCore.Mvc.Internal.TypeActivatorCache.CreateInstance[TInstance](IServiceProvider serviceProvider, Type implementationType) at Microsoft.AspNetCore.Mvc.Controllers.DefaultControllerActivator.Create(ControllerContext controllerContext) at Microsoft.AspNetCore.Mvc.Controllers.DefaultControllerFactory.CreateController(ControllerContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__26.MoveNext()

Could anyone please help me on this? Any configuration missing for Serilog?

like image 412
Sanket Avatar asked Nov 20 '16 06:11

Sanket


People also ask

What is ILogger in c# net?

ILoggerFactory is a factory interface that we can use to create instances of the ILogger type and register logging providers. It acts as a wrapper for all the logger providers registered to it and a logger it creates can write to all the logger providers at once.

Does Serilog use ILogger?

But to my surprise, Serilog is using it's own ILogger interface - bummer!

How do I enable Serilog?

Structured Logging with Serilog. To enable structured logging with the File Sink, we need to add a JSON formatter as a Parameter to the Settings. Let's add new Sink to our appSettings. json/Serilog. Add the below code as the sink.

What is Serilog in asp net core?

Serilog is a . NET library that provides diagnostic logging to files, the console, and almost everywhere you would like. Serilog can be used in classic . NET Framework applications and for applications running on the latest and greatest .


3 Answers

Try to do following thing in your controller.

    ILogger<HomeController> logger = null;
    public HomeController(ILogger<HomeController> _logger)
    {
        logger = _logger;
    }
like image 196
dotnetstep Avatar answered Oct 06 '22 19:10

dotnetstep


If you need to use ILogger (from Serilog) instead of ILogger<HomeController> (from Microsoft.Extensions.Logging), you can register ILogger on your Startup class:

services.AddSingleton(Log.Logger);
like image 36
Marcello Avatar answered Oct 06 '22 21:10

Marcello


Which of the following two lines do you have in your controller?

using Serilog;
using Microsoft.Extensions.Logging;

If it's the former (using Serilog;) then that's probably your problem.

When you register the service, you're essentially saying "When a constructor asks for an Microsoft.Extensions.Logging.ILogger, pass them a Serilog instance because I'm using Serilog for my logging", but then in your constructor you aren't asking for Microsoft.Extensions.Logging.ILogger, you're asking for Serilog.ILogger and your application is getting confused, because you haven't defined an service to be injected for Serilog.ILoger, you've defined one for Microsoft.Extensions.Logging.ILogger

Remember that you are implementing Microsoft's ILogger interface: your constructor doesn't need to know that you're using Serilog... in fact, you don't want it to! The entire point is that you can swap Serilog out for a different logger at any time without having to change your code.

Change using Serilog; to using Microsoft.Extensions.Logging; in your constructor, and you'll be requesting the correct service type

like image 26
Jon Story Avatar answered Oct 06 '22 21:10

Jon Story