Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle deprecation of IWebHostBuilder.UseSerilog() when IWebHostBuilder is still needed?

Tags:

serilog

The UseSerilog() extension is deprecated* for IWebHostBuilder in serilog-aspnetcore version 5.0.0. However, I'm still using a IWebHostBuilder and a Startup class (aspnetcore 6), and IWebHostBuilder is not deprecated.

Since deprecation implies future removal, how should I leverage Serilog going forward?


* Reference: https://github.com/serilog/serilog-aspnetcore/releases/tag/v5.0.0

mark IWebHostBuilder extensions as obsolete on platforms with IHostBuilder

like image 366
daniel327 Avatar asked Sep 01 '25 03:09

daniel327


1 Answers

I was able to get this to work by switching to IHostBuilder instead of IWebHostBuilder. The key in my case was to call ConfigureWebHostDefaults (or ConfigureWebHost), where you can then utilize an IWebHostBuilder.

In this way, I could call UseSerilog on the IHostBuilder while still utilizing the Startup class as before with an IWebHostBuilder.

Example:

public static void Main(string[] args)
{
    // temp initial logging
    Log.Logger = new LoggerConfiguration()
        .WriteTo.Console()
        .CreateBootstrapLogger();

    using var app =
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webHostBuilder
                => webHostBuilder.ConfigureAppConfiguration((hostingContext, config) =>
                        _ = config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                            .AddJsonFile("appsettings.json", false, true))
                    .UseStartup<Startup>())
            .UseSerilog(
                (hostingContext, loggerConfig) =>
                    loggerConfig
                        .ReadFrom.Configuration(hostingContext.Configuration)
                        .Enrich.FromLogContext(),
                writeToProviders: true)
            .Build();
    app.Run();
}
like image 116
daniel327 Avatar answered Sep 08 '25 12:09

daniel327