Skip to Main Menu

Serilog: Log.CloseAndFlush();

You really should close the door behind you.

I have spoken to many people over recent years about their use of Serilog and how it helps their development. One of the most common issues I encounter when people are starting out, relates to the Hello World console app.

Someone may start out with a simple example using the Literate sink such as the code below.

static void Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
        .WriteTo.LiterateConsole()
        .CreateLogger();

    Log.Information("Hello World... it's {Name}", Environment.UserName);
}

Then they move onto using a more advanced or feature rich sink such as Seq, at the same time logging many more events.

static void Main(string[] args)
{
   Log.Logger = new LoggerConfiguration()
      .WriteTo.LiterateConsole()
      .WriteTo.Seq("http://localhost:5341")
      .CreateLogger();

   foreach (var i in Enumerable.Range(0, 10000))
   {
      Log.Information("Hello loop {Counter}", i);   
   } 
}

Often what occurs is the app exits without writing the events expected to the respective sinks.

A quick win in this case is Log.CloseAndFlush(). It may sound simple, however it is a gotcha for many starting out with Serilog. This will call dispose of sinks that implement this pattern.

For example:

static void Main(string[] args)
{
   Log.Logger = new LoggerConfiguration()
      .WriteTo.LiterateConsole()
      .WriteTo.Seq("http://localhost:5341")
      .CreateLogger();

   foreach (var i in Enumerable.Range(0, 10000))
   {
      Log.Information("Hello loop {Counter}", i);   
   }
   Log.CloseAndFlush()
}

An alternative is to use a using statement.

For example:

static void Main(string[] args)
{
   using (var log = new LoggerConfiguration()
         .WriteTo.LiterateConsole()
         .WriteTo.Seq("http://localhost:5341")
         .CreateLogger())
   {
      foreach (var i in Enumerable.Range(0, 10000))
      {
         Log.Information("Hello loop {Counter}", i);   
      }
   }
}

It should be noted, that it is the responsibility of a sink to perform the flush of events when finalising. This is by design due to the number and variety of sinks the Serilog eco-system supports.

There is more detail over on the Serilog Wiki.

Get Amongst It!!

comments powered by Disqus