serilog / serilog-sinks-async

An asynchronous wrapper for Serilog sinks that logs on a background thread
Apache License 2.0
231 stars 30 forks source link

Log file is not created after Log.CloseAndFlush() is called #75

Closed Azatey closed 3 years ago

Azatey commented 3 years ago

I have a .net core worker type project with the following code:

using System;
using System.Threading;
using Serilog;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .WriteTo.Console()
                .WriteTo.Async(a => a.File("logs/app.log", rollingInterval: RollingInterval.Day))
                .CreateLogger()
                .ForContext<Program>();

            try
            {
                Log.Debug("Initiating startup");
                throw new Exception("Oopsie!"); // Here is the Host creation code that throws an exception
                Log.Debug("Graceful app completion");
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "An unhandled exception occured during startup");
            }
            finally
            {
                Log.CloseAndFlush();
                // Thread.Sleep(100);
            }
        }
    }
}

For some reason in this configuration the log files are not being created. In order to this code to work one of these changes have to be done:

  1. Uncomment the line with Thread.Sleep(100);. This tiny timeout fixes the issue.
  2. Remove/Comment the line with .ForContext<Program>();. But then I'll lose the context, which is not what I want
  3. Get rid of Async sink wrapper.
  4. Set minimum level to Verbose. Which is not an option, since all unnecessary logs will flood log file.
  5. Removing rolling interval parameter / Changing it to Infinite (default)

Looks like something taking longer than needed to flush the logs to file and this code specifically doesn't work when Log.Fatal(...) is located under catch block.

My environment:

augustoproiete commented 3 years ago

Duplicate of https://github.com/serilog/serilog-sinks-async/issues/76