Search code examples
c#asp.net-coreasp.net-web-apiasp.net-2.0serilog

ASP.NET Core 2.2 - Serilog | Missing out on events


New to ASP.NET Core and trying to reuse my already configured Serilog from another [Core] library. Here is my setup -

Test.sln
  Test.Core (project)
      - Serilog init config
      - Autofac dependency injection
      - Other stuff
  Test.WebAPI (project)
      - Configured Autofac module from my Core library in ConfigureContainer method.

Got the base setup figured out. Any services/controllers I make are receiving the dependencies from the registrations I've done in Core library's Autofac module (including the logging as well, but only if I explicitly call _logger.Information / _logger.Debug, etc. and gets printed to both console and log file as configured in Serilog config).

It seems ASP.NET has it's own logger and is using its own logger to log all events, such as these ones - https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2#sample-logging-output

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/api/todo/0
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Executing action method TodoApi.Controllers.TodoController.GetById (TodoApi) with arguments (0) - ModelState is Valid
info: TodoApi.Controllers.TodoController[1002]
      Getting item 0
warn: TodoApi.Controllers.TodoController[4000]
      GetById(0) NOT FOUND

I am trying to re-route events logged by ASP.NET's logger to my own logger and have one logger all around, but cannot figure out how. Can anyone point me in the right direction, please? Thanks in advance!


Solution

  • In my case I have to set Serilog's ILogger from Core library in Startup.cs/Configure() method.

    Program.cs

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
              .ConfigureServices(services => services.AddAutofac())
              .UseStartup<Startup>()
              .UseSerilog(); // Added this line as per docs
    

    Startup.cs

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IZLogger zLogger)
    {
        ...
        Log.Logger = zLogger.GetCurrentClassLogger<Startup>(); // Set Serilog's ILogger from Core library
        app.UseSerilogRequestLogging(); // Added this line as per docs
        ...
    }
    

    Example log:

    2019-07-22 19:01:03.179 -04:00 | [INFO] | Request starting HTTP/1.1 GET https://localhost:5001/favicon.ico  
    2019-07-22 19:01:03.180 -04:00 | [INFO] | HTTP GET /favicon.ico responded 404 in 0.394846 ms
    2019-07-22 19:01:03.181 -04:00 | [INFO] | Request finished in 1.8292ms 404 text/plain