Skip to content

Two-stage initialization with exception during UseSerilog is not logged to files #75

@cremor

Description

@cremor

Example:

Log.Logger = new LoggerConfiguration()
    .WriteTo.Debug()
    .WriteTo.Console()
    .WriteTo.File(BootstrapLogFilePath, LogEventLevel.Error)
    .CreateBootstrapLogger();
	
var builder = WebApplication.CreateBuilder(args);
	
builder.Host.UseSerilog((context, services, loggerConfiguration) => loggerConfiguration
    .ReadFrom.Configuration(context.Configuration)
    .ReadFrom.Services(services));

If an exception happens in the configureLogger action passed to UseSerilog (e.g. because the configuration in appsettings.json is invalid) then the resulting exception will be logged in the console and debug output, but it will not be logged in the file.

The Serilog SelfLog logs a related exception: "Caught exception while emitting to sink Serilog.Core.Sinks.RestrictedSink: System.ObjectDisposedException: Cannot write to a closed TextWriter."
It looks like the bootstrap logger is already disposed, but the new logger doesn't exist yet. So the exception can't be logged to any file.

Would it be possible to only dispose the bootstrap logger once the new logger is fully loaded? Then the exception would be logged to the file sink from the bootstrap logger.

In any case, exceptions that happen during the configureLogger action passed to UseSerilog should be written to the SelfLog.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions