March 31st, 2020

Application Insights – Use case for TelemetryClient flush calls

Developer Support
Cloud Solution Architects

In this post, Azure consultant Adel Ghabboun explains when to use TelemetryClient.Flush() method.


Many of us may already know, Application Insights SDK provides classes to help instrument and monitor web applications. Telemetry Client is one of those classes that can be used to send custom telemetry to the Application Insights service.

Telemetry Client includes a Flush() method to flush the in memory buffer at the shutdown activity of the Application. Normally, the SDK sends data typically every 30 sec or whenever the buffer is full (500 items) and no need to manually call Flush() method for web applications except when the application is about to be shut down.

Ideally, the right usage pattern for Flush method is when the application encountered something unexpected, shutting down and needs to upload exception before crashing. [See below Code snippet]

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Microsoft.AspNetCore.Hosting.IApplicationLifetime applicationLifetime)
{
             
   applicationLifetime.ApplicationStopping.Register(OnShutdown);
}
        
private void OnShutdown()
{
   TelemetryClient client = new TelemetryClient ();
   client.Flush();
   Thread.Sleep(5000);
}

Calling the method more often (like every request ) can starve the thread pool and will lead to performance problems.

As a result, it is strongly not recommended to use Flush() method on a happy path.

Author

Developer Support
Cloud Solution Architects

Microsoft Developer Support helps software developers rapidly build and deploy quality applications for Microsoft platforms.

0 comments

Discussion are closed.