Adding custom properties for each request in Application Insights metrics

后端 未结 5 2008
孤街浪徒
孤街浪徒 2020-11-29 03:42

I d\'like to add custom properties to metrics taken by Application Insights to each request of my app. For example, I want to add the user login and the ten

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 04:45

    You can use the static HttpContext.Current's Items dictionary as a short term (near stateless) storage space to deliver your custom property values into the default telemetry handler with a custom ITelemetryInitializer

    Implement handler

    class AppInsightCustomProps : ITelemetryInitializer
    {
        public void Initialize(ITelemetry telemetry)
        {
            var requestTelemetry = telemetry as RequestTelemetry;
            // Is this a TrackRequest() ?
            if (requestTelemetry == null) return;
    
            var httpCtx = HttpContext.Current;
            if (httpCtx != null)
            {
                var customPropVal = (string)httpCtx.Items["PerRequestMyCustomProp"];
                if (!string.IsNullOrWhiteSpace(customPropVal))
                {
                    requestTelemetry.Properties["MyCustomProp"] = customPropVal;
                }
            }
        }
    }
    

    Hook it in. Put this inside Application_Start in global.asax.cs

    TelemetryConfiguration.Active.TelemetryInitializers.Add(new AppInsightCustomProps());
    

    Program the desired custom property, anywhere in your request pipeline have something like

    if (HttpContext.Current != null)
    {
        HttpContext.Current.Items["PerRequestMyCustomProp"] = myCustomPropValue;
    }
    

提交回复
热议问题