8

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; and ILogger 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
  • 762
  • 1
  • 10
  • 24

3 Answers3

8

Change expected type from ILogger logger to ILogger<CustomersController> logger:

private readonly ILogger _logger;

public CustomersController(ILogger<CustomersController> logger)
{
    _logger = logger;
}
Set
  • 47,577
  • 22
  • 132
  • 150
  • Thanks. I reset my edits to test this and it worked. Do we know why? :-) – leon Aug 30 '17 at 13:09
  • 2
    @leon look into [Why ASP.NET Core DI knows how to resolve ILogger, but not ILogger?](https://stackoverflow.com/questions/38255053/why-asp-net-core-di-knows-how-to-resolve-iloggert-but-not-ilogger) – Set Aug 30 '17 at 13:19
3

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.

Nicholas Blumhardt
  • 30,271
  • 4
  • 90
  • 101
-3

You can follow the below code for use.

//using Microsoft.Extensions.Logging;

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
            //Logger for File
            loggerFactory.AddFile("FilePath/FileName-{Date}.txt");

        }
    }

    //Add following code into Controller:

    private readonly ILogger<ControllerName> _log;

    public ControllerConstructor(ILogger<ControllerName>logger)
     {
          _log = logger;
     }
    [HttpGet]
    public ActionResult GetExample()
    {
        try
        {
            //TODO:Log Informationenter code here
            _log.LogInformatio("LogInformation");
        }
        catch (Exception exception)
        {
             //TODO: Log Exception
             _log.LogError(exception, exception.Message + "\n\n");
        } 
        return view("viewName");
    }
Vineeth Sai
  • 3,389
  • 7
  • 23
  • 34