datalust/serilog-sinks-seq

Log.CloseAndFlush() does not ensure that all events are written to the seq server

StefanOssendorf opened this issue · 2 comments

Hello,

the following program does not send any entries to the seq-server but outputs all on the console.

class Program
    {
        static void Main(String[] args)
        {
            Console.WriteLine("Hello World!");

            var logger = new LoggerConfiguration()
                .WriteTo.Console()
                .WriteTo.Seq("http://localhost:5341", LogEventLevel.Verbose, eventBodyLimitBytes: null, compact: true)
                .MinimumLevel.Verbose()
                .CreateLogger()
                .ForContext("Application", "SerilogTestContext");

            Log.Logger = logger;

            try
            {
                for (int i = 0; i < 20; i++)
                {
                    logger.Information($"Just some information in iteration {i}");

                    if (i == 15)
                    {
                        throw new InvalidOperationException();
                    }
                }
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
    }

Hi Stefan!

Thanks for getting in touch. The problem here is that the return value of CreateLogger() is the disposable, root logger, with the sink attached:

                .CreateLogger()

But the next call just returns a child, contextual logger, that sends events to the root one:

                .ForContext("Application", "SerilogTestContext");

It's this child logger that you're assigning to Log.Logger, so, when it's CloseAndFlush()ed, only that child logger is closed (a no-op), and the root logger with the Seq sink attached just floats around until it's GCed.

I think what you're looking for is Enrich.WithProperty():

            Log.Logger = new LoggerConfiguration()
                .Enrich.WithProperty("Application", "SerilogTestContext")
                .WriteTo.Console()
                .WriteTo.Seq("http://localhost:5341", compact: true)
                .CreateLogger();

Hopefully this sorts things out for you, but let me know if you still hit any trouble with it.

Best regards,
Nick

Hi Nick.

Thank you very much for your detailed explanation. Switchting to Enrich solved the problem.

Thanks again :-)