Search code examples
c#loggingserilog

What is the preferred way to configure logging with Serilog in NetCore when using a generic Host?


How should Serilog be configured if you want to use it within NetCore and a generic Host (or IHost), not a WebHost or something else?

There are the two options I found:

  1. Use .UseSerilog() from the Serilog.Extensions.Hosting NuGet package:
var host = Host.CreateDefaultBuilder()
                    .UseSerilog()
                    .UseSystemd()
                    .UseWindowsService()
                    .Build();
  1. Use .ConfigureLogging() and .AddSerilog() from the Serilog NuGet package:
.ConfigureLogging(
    logging =>
    {
        logging.AddSerilog();
    });

So there are two questions now:

  1. Do both options result in the same behaviour and if not, what's the difference?
  2. Which method should be used preferred (Or are they equal and you can use as you like)?

Solution

  • From Serilog.AspNetCore(version 5.0.0) on, the second option is marked as deprecated and the generic host option (Option 1) should be used. For example, with a web host builder:

    private static IHostBuilder CreateHostBuilder(string[] args, string currentLocation) =>
            Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(
                webBuilder =>
                {
                    webBuilder.UseContentRoot(currentLocation);
                    webBuilder.UseStartup<Startup>();
                })
                .UseSerilog();