Search code examples
c#loggingdependency-injection.net-coreserilog

Net Core 3.0 and Serilog producing output like Microsoft.Extensions.Logging


I have a simple web app using .Net Core 3.0.

In my host builder I do this:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
                    .ReadFrom.Configuration(hostingContext.Configuration)
                    .Enrich.FromLogContext()
                    .WriteTo.Console());

I then try to implement it in another project (simple dll using netcoreapp3.0) being referenced by the web app project:

using using Microsoft.Extensions.Logging;
...
private readonly ILogger<MyClass> _logger;

public MyClass(ILogger<MyClass> logger){
  _logger = logger;
  ...
  Log.Logger.Information("this is a test {test}", command.GetType().Name);

  _logger.LogInformation("Command received: {CommandType}", command.GetType().Name);
}
...

The static logger works fine but the _logger's output is as if I use the default logging. But as far as I understand from reading this, the host builder now has the ILoggerFactory replaced and should output Serilog styled output.

These are my two outputs, first from the static and then from _logger

How can I get the _logger output to be as neat as the Serilog one?


Solution

  • The problem I was experiencing was that whenever I caught a queue-event, the log used Microsoft.Extensions.Logging styled logging.

    This seems to be because the event listener was somehow registered BEFORE the logging factory was replaced but executed AFTER, which led to the weird logging. My solution was doing this:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
                        .ReadFrom.Configuration(hostingContext.Configuration)
                        .Enrich.FromLogContext()
                        .WriteTo.Console());
                        webBuilder.UseStartup<Startup>();
                    });