We are having a bunch of problems (read long response times) with a couple of projects in production and wanted to see exactly what was happening on the server. I then proceeded
Below is our implementation of a OWIN Middleware for Application Insights.
///
/// Extensions to help adding middleware to the OWIN pipeline
///
public static class OwinExtensions
{
///
/// Add Application Insight Request Tracking to the OWIN pipeline
///
///
public static void UseApplicationInsights(this IAppBuilder app) => app.Use(typeof(ApplicationInsights));
}
///
/// Allows for tracking requests via Application Insight
///
public class ApplicationInsights : OwinMiddleware
{
///
/// Allows for tracking requests via Application Insight
///
///
public ApplicationInsights(OwinMiddleware next) : base(next)
{
}
///
/// Tracks the request and sends telemetry to application insights
///
///
///
public override async Task Invoke(IOwinContext context)
{
// Start Time Tracking
var sw = new Stopwatch();
var startTime = DateTimeOffset.Now;
sw.Start();
await Next.Invoke(context);
// Send tracking to AI on request completion
sw.Stop();
var request = new RequestTelemetry(
name: context.Request.Path.Value,
startTime: startTime,
duration: sw.Elapsed,
responseCode: context.Response.StatusCode.ToString(),
success: context.Response.StatusCode >= 200 && context.Response.StatusCode < 300
)
{
Url = context.Request.Uri,
HttpMethod = context.Request.Method
};
var client = new TelemetryClient();
client.TrackRequest(request);
}
}