Application Shutdown in ASP.NET Core

Handling flushing of the application insights messages when asp.net core shutsdown

Advertisements

When running a ASP.NET Core web application there are cases when you need to do some logic when the application stops. A example: you are logging and have to flush the last message to the log (Application Insights). In that case you need can add an event in the Configure method. In this post I show a short example of how to do this.

Register the Shutdown event

The Configure in the Startup class can have the following parameters:

  • IApplicationBuilder
  • IHostingEnvironment
  • ILoggerFactory
  • IApplicationLifetime

In the IApplicationLifetime interface you can register an event that is triggered when the application stops:

public class Startup
{
    public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime)
    {
        applicationLifetime.ApplicationStopping.Register(OnShutdown);
    }

    private void OnShutdown()
    {
         //this code is called when the application stops
    }
}

The OnShutdown method is now wired to run when the application stops.

Apply to Application Insights

By default Application Insights buffers messages to send them in bulk to the server. When you do not flush your log, the chance is that you miss messages when your application is terminates. To solve this you need to flush buffer:

public class Startup
{
    private TelemetryClient _telemetryClient;

    public Startup(IHostingEnvironment env)
    {
       ...

       _telemetryClient = new TelemetryClient()
       {
            InstrumentationKey = Configuration["ApplicationInsights:InstrumentationKey"],
       };

       ...
    }

    public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime)
    {
        applicationLifetime.ApplicationStopping.Register(OnShutdown);

        ...
    }

    private void OnShutdown()
    {
         _telemetryClient.Flush();
         //Wait while the data is flushed
         System.Threading.Thread.Sleep(1000);
    }
}

With these few lines of code, you will not miss any of you important logging messages in the future.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s