Skip to content

Logger is not disposed along with ServiceProvider #47

Closed
@aleksey-s902

Description

@aleksey-s902

Repro: https://github.com/aleksey-s902/SerilogProviderNotDisposedRepro

        static void Main(string[] args)
        {
            var serviceProvider = new ServiceCollection()
                .AddLogging(builder =>
                {
                    builder.AddFile("test.log");
                })
                .BuildServiceProvider();

            var logger = serviceProvider.GetService<ILogger<Program>>();
            logger.LogError("test");
            
            serviceProvider.Dispose();
            // Thread.Sleep(5000);
        }

Problem with this code: the log file isn't written. There is obviously a race condition because if I uncomment Thread.Sleep, the log file appears correctly. My understanding of what happening there is:

  • AddFile adds an async file writer which runs in a background thread
  • Application shuts down before the background thread has a chance to write the log file
  • Normally, this is prevented by disposing logger before shutdown. I would expect that in this case ServiceProvider would dispose the logger. However, that isn't happening.

As to why it isn't happening: I suppose that's caused by the same reason as aspnet/Hosting#1466. AddSerilog register an instance of SerilogLoggerProvider, and ServiceProvider won't dispose anything added as an instance.

Workaround: dispose the logger provider manually:

serviceProvider.GetService<ILoggerProvider>().Dispose();

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