Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(Guidance 2022.2.1.14 and later): improve Serilog initialization error handling #255

Open
vvdb-architecture opened this issue Aug 23, 2024 · 0 comments

Comments

@vvdb-architecture
Copy link
Contributor

When a service starts and something happens during the initialization just before the host is built, we see this error message:

[16:59:24 INF] Starting up MyService.....
[16:59:24 FTL] Unhandled exception
System.InvalidOperationException: No service for type 'Microsoft.Extensions.Hosting.IHost' has been registered.
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Extensions.Hosting.HostBuilder.ResolveHost(IServiceProvider serviceProvider, DiagnosticListener diagnosticListener)
   at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()
   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()

This is hard to debug, as there is almost no exception tracing available during the execution of var app = builder.Build();

It was found that in many cases, this is a problem in Serilog initialization:

    // Configure logging using Serilog
    builder.Host.UseSerilog((ctx, lc) => lc.ReadFrom.Configuration(ctx.Configuration));

When an exception occurs during the execution of lc.ReadFrom.Configuration(ctx.Configuration)), the exception is swallowed, the host initialization fails and we get the above exception.

To report the exception, the Guidance should generate the following code instead:

    // Configure logging using Serilog
    builder.Host.UseSerilog((ctx, lc) =>
    {
        try
        {
            lc.ReadFrom.Configuration(ctx.Configuration);
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Failed to configure Serilog");
            throw;
        }
    });

This will give the static logger a chance to log the exception before issuing the above unhandled exception.

Note that the exception is rethrown. This is intentional: we want the host construction to fail, since anything running without a correctly configured logging system is problematic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant