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

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"



Solution 1:[1]

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();
}

Solution 2:[2]

I Solved with:

var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 daniel327
Solution 2 Gabriel_ES