How do I enable Application Insights server telemetry on WebApi project that uses OWIN?

后端 未结 3 499
一整个雨季
一整个雨季 2021-02-05 09:37

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

3条回答
  •  自闭症患者
    2021-02-05 10:16

    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);
    
        }
    }
    

提交回复
热议问题