Skip to content

Logging Exceptions through UseExceptionHandler #1311

Open
@woutervanranst

Description

@woutervanranst

It would seem reasonable to log errors in the exception handler, and configure it using the modified builder (as per #796 (comment)).

However, the context available in the UseExceptionHandler method has its services disposed.

Is this expected behavior, or how would I proceed to log the error with the logging infrastructure configured in the IHost.ConfigureLogging?

var _ = new CommandLineBuilder(rootCommand)
    .UseHost(_ => Host.CreateDefaultBuilder(), host =>
    {
        host
            .ConfigureAppConfiguration( ... )
            .ConfigureLogging( ... )
            .ConfigureServices( ... );
    })
    .UseDefaults()
    .UseExceptionHandler((e, context) =>
    {
            // throws 'System.ObjectDisposedException: 'Cannot access a disposed object. Object name: 'IServiceProvider'.'
            var logger = context.GetHost().Services.GetRequiredService<ILoggerFactory>(); 
            logger.LogError(e);
    })
    .Build();
    rootCommand.Invoke(args);

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions