Skip to content

Instantly share code, notes, and snippets.

@benfoster
Created August 8, 2016 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benfoster/1240d93cc18a0742969c8bf12254ed2c to your computer and use it in GitHub Desktop.
Save benfoster/1240d93cc18a0742969c8bf12254ed2c to your computer and use it in GitHub Desktop.
Serilog Application Shutdown
using Serilog;
using Serilog.Core;
using System;
using System.Web.Hosting;
namespace Merchant.Api.Logging
{
/// <summary>
/// Detects application pool shutdowns and ensures all batched log entries
/// are flushed.
/// </summary>
public class LoggerShutdownDetector : IRegisteredObject
{
private readonly ILogger _logger;
public LoggerShutdownDetector(ILogger logger)
{
if (logger == null) throw new ArgumentNullException(nameof(logger));
_logger = logger;
}
/// <summary>
/// Registers the shutdown detector with the hosting environment.
/// </summary>
public void Initialize()
{
HostingEnvironment.RegisterObject(this);
}
/// <summary>
/// Called when a shutdown is detected.
/// https://msdn.microsoft.com/en-us/library/system.web.hosting.iregisteredobject.stop(v=vs.110).aspx
/// </summary>
/// <param name="immediate">true to indicate the registered object should unregister from the hosting environment before returning; otherwise, false.</param>
public void Stop(bool immediate)
{
try
{
_logger.Information("Application Stopping");
// Ensure any batched sinks are flushed
// https://github.com/serilog/serilog/wiki/Lifecycle-of-Loggers
(_logger as Logger)?.Dispose();
}
catch
{
// Swallow the exception as Stop should never throw
}
finally
{
HostingEnvironment.UnregisterObject(this);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment