Created
August 8, 2016 09:52
-
-
Save benfoster/1240d93cc18a0742969c8bf12254ed2c to your computer and use it in GitHub Desktop.
Serilog Application Shutdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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