0

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!

1
  • I checked this link. Don't understand this line - Remove ILoggerFactory parameters and any Add*() calls on the logger factory in Startup.cs. Where should I remove this from? Commented Jul 22, 2019 at 19:02

2 Answers 2

1

To "silence" ASP.NET default logs you need to add this to your appsettings.json:

"Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Warning",
      "System": "Warning"
    }
  }

Then default logger will only log everything with "Warning" or lower levels (there are 6 levels of logs: Trace, Debug, Information, Warning, Error Critical). Also, in order to enable Serilog you just need to add this package:

<PackageReference Include="Serilog.AspNetCore" Version="#version#" />

And add this to your Program.cs:

WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseSerilog(); //this line

Then you can simply inject ILogger<T> with DI and it will use Serilog with your configuration. Also, it will encapsulate your Serilog so later it will be easier to use other logging frameworks

Update: In order to remove previously configured providers try to add this line:

new WebHostBuilder()
.ConfigureLogging(builder => builder.ClearProviders()) // <--here
Sign up to request clarification or add additional context in comments.

5 Comments

Apologies for the confusion! Fixed my question. I would like to reroute all log lines ASP.NET prints to my Serilog logger class. I have indeed tried removing Logging from appsettings.json, which only silences ASP.NETs log, but it's not redirecting them (controller calls, time elapsed, etc.) to my serilog logger.
Thank you! I have tried this and indeed the 'events' printed by ASP.NET are gone. But my Serilog is still not catching them :( It is only printing whatever I print explicitly (i.e. still missing the 'events' that were usually printed by ASP.NET)
@PhaniAnne I'm not sure it is possible to re-route MS logs into Serilog. You can just remove/silence logs by setting the level. If you still need to hook into the HTTP request processing pipeline then there is only way is to write custom middleware and use Serilog there
This section describes it - github.com/serilog/serilog-aspnetcore#request-logging-300-, but I can't seem to get it to work.
@Olegl Please take a look at the solution I posted above. Let me know what you think :) stackoverflow.com/a/57154844/1946418
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.