Beispiel #1
0
        private static SpanContext ExtractPropagatedContext(HttpRequest request)
        {
            try
            {
                // extract propagation details from http headers
                var requestHeaders = request.Headers;

                if (requestHeaders != null)
                {
                    var headersCollection = new DictionaryHeadersCollection();

                    foreach (var header in requestHeaders)
                    {
                        string   key    = header.Key;
                        string[] values = header.Value.ToArray();

                        if (key != null && values.Length > 0)
                        {
                            headersCollection.Add(key, values);
                        }
                    }

                    return(B3SpanContextPropagator.Instance.Extract(headersCollection));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error extracting propagated HTTP headers.");
            }

            return(null);
        }
        private static IHeadersCollection InjectContext(string traceId, string spanId, string samplingPriority)
        {
            IHeadersCollection headers = new DictionaryHeadersCollection();

            headers.Add(HttpHeaderNames.TraceId, traceId);
            headers.Add(HttpHeaderNames.ParentId, spanId);
            headers.Add(HttpHeaderNames.SamplingPriority, samplingPriority);
            return(headers);
        }
        public async Task <APIGatewayProxyResponse> InvokeAPIGatewayProxyAsync(
            Func <APIGatewayProxyRequest, ILambdaContext, Task <APIGatewayProxyResponse> > asyncHandler,
            APIGatewayProxyRequest request,
            ILambdaContext context,
            string operationName = null,
            IEnumerable <KeyValuePair <string, string> > tags = null)
        {
            IHeadersCollection headersCollection = null;

            if (TelemetryConfiguration.ContextPropagationEnabled)
            {
                headersCollection = new DictionaryHeadersCollection(request.MultiValueHeaders);
            }

            using (var tracker = new TelemetryTracker(context, operationName, tags, headersCollection))
            {
                try
                {
                    APIGatewayProxyResponse apiGatewayProxyResponse = await asyncHandler(request, context);

                    if (!apiGatewayProxyResponse.IsSuccessStatusCode())
                    {
                        tracker.SetErrorCounter();

                        // Preserve the legacy logging.
                        LambdaLogger.Log($"[ERR] Invoking lambda function. Http status code: {apiGatewayProxyResponse.StatusCode}. Response body: {apiGatewayProxyResponse.Body}{Environment.NewLine}");
                    }

                    return(apiGatewayProxyResponse);
                }
                catch (Exception e)
                {
                    tracker.SetException(e);
                    throw;
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AspNetCoreMvc2Integration"/> class.
        /// </summary>
        /// <param name="actionDescriptor">An ActionDescriptor with information about the current action.</param>
        /// <param name="httpContext">The HttpContext for the current request.</param>
        public AspNetCoreMvc2Integration(object actionDescriptor, object httpContext)
        {
            try
            {
                _httpContext = httpContext;
                var request = _httpContext.GetProperty("Request").GetValueOrDefault();

                GetTagValues(
                    actionDescriptor,
                    request,
                    out string httpMethod,
                    out string host,
                    out string resourceName,
                    out string url,
                    out string controllerName,
                    out string actionName);

                SpanContext propagatedContext = null;
                var         tracer            = Tracer.Instance;

                if (tracer.ActiveScope == null)
                {
                    try
                    {
                        // extract propagated http headers
                        var requestHeaders = request.GetProperty <IEnumerable>("Headers").GetValueOrDefault();

                        if (requestHeaders != null)
                        {
                            var headersCollection = new DictionaryHeadersCollection();

                            foreach (object header in requestHeaders)
                            {
                                var key    = header.GetProperty <string>("Key").GetValueOrDefault();
                                var values = header.GetProperty <IList <string> >("Value").GetValueOrDefault();

                                if (key != null && values != null)
                                {
                                    headersCollection.Add(key, values);
                                }
                            }

                            propagatedContext = SpanContextPropagator.Instance.Extract(headersCollection);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Error extracting propagated HTTP headers.");
                    }
                }

                _scope = tracer.StartActive(OperationName, propagatedContext);
                var span = _scope.Span;

                span.DecorateWebServerSpan(
                    resourceName: resourceName,
                    method: httpMethod,
                    host: host,
                    httpUrl: url);

                span.SetTag(Tags.AspNetController, controllerName);
                span.SetTag(Tags.AspNetAction, actionName);

                // set analytics sample rate if enabled
                var analyticsSampleRate = tracer.Settings.GetIntegrationAnalyticsSampleRate(IntegrationName, enabledWithGlobalSetting: true);
                span.SetMetric(Tags.Analytics, analyticsSampleRate);
            }
            catch (Exception) when(DisposeObject(_scope))
            {
                // unreachable code
                throw;
            }
        }
        private AspNetAmbientContext(string integrationName, object httpContext)
        {
            try
            {
                Tracer       = Tracer.Instance;
                _httpContext = httpContext;

                var request  = _httpContext.GetProperty("Request").GetValueOrDefault();
                var response = _httpContext.GetProperty("Response").GetValueOrDefault();

                GetTagValues(
                    request,
                    out string absoluteUri,
                    out string httpMethod,
                    out string host,
                    out string resourceName);

                if (httpMethod == StartupDiagnosticMethod)
                {
                    // An initial diagnostic HttpContext is created on the start of many web applications
                    AbortRegistration = true;
                    return;
                }

                RegisterForDisposalWithPipeline(response, this);

                SpanContext propagatedContext = null;

                if (Tracer.ActiveScope == null)
                {
                    try
                    {
                        // extract propagated http headers
                        var requestHeaders = request.GetProperty <IEnumerable>("Headers").GetValueOrDefault();

                        if (requestHeaders != null)
                        {
                            var headersCollection = new DictionaryHeadersCollection();

                            foreach (object header in requestHeaders)
                            {
                                var key    = header.GetProperty <string>("Key").GetValueOrDefault();
                                var values = header.GetProperty <IList <string> >("Value").GetValueOrDefault();

                                if (key != null && values != null)
                                {
                                    headersCollection.Add(key, values);
                                }
                            }

                            propagatedContext = SpanContextPropagator.Instance.Extract(headersCollection);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Error extracting propagated HTTP headers.");
                    }
                }

                _rootScope = Tracer.StartActive(TopLevelOperationName, propagatedContext);

                RegisterForDisposal(_rootScope);

                var span = _rootScope.Span;

                span.DecorateWebServerSpan(
                    resourceName: resourceName,
                    method: httpMethod,
                    host: host,
                    httpUrl: absoluteUri);

                var statusCode = response.GetProperty <int>("StatusCode");

                if (statusCode.HasValue)
                {
                    span.SetTag(Tags.HttpStatusCode, statusCode.Value.ToString());
                }

                var analyticSampleRate = Tracer.Settings.GetIntegrationAnalyticsSampleRate(integrationName, enabledWithGlobalSetting: true);
                span.SetMetric(Tags.Analytics, analyticSampleRate);
            }
            catch (Exception ex)
            {
                // Don't crash client apps
                Log.Error(ex, $"Exception when initializing {nameof(AspNetAmbientContext)}.");
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AspNetCoreMvc2Integration"/> class.
        /// </summary>
        /// <param name="actionDescriptor">An ActionDescriptor with information about the current action.</param>
        /// <param name="httpContext">The HttpContext for the current request.</param>
        public AspNetCoreMvc2Integration(object actionDescriptor, object httpContext)
        {
            try
            {
                _httpContext = httpContext;
                string httpMethod   = null;
                string resourceName = null;
                string host         = null;
                string url          = null;

                if (actionDescriptor.TryGetPropertyValue("ControllerName", out string controllerName))
                {
                    controllerName = controllerName?.ToLowerInvariant();
                }

                if (actionDescriptor.TryGetPropertyValue("ActionName", out string actionName))
                {
                    actionName = actionName?.ToLowerInvariant();
                }

                if (_httpContext.TryGetPropertyValue("Request", out object request) &&
                    request.TryGetPropertyValue("Method", out httpMethod))
                {
                    httpMethod = httpMethod?.ToUpperInvariant();
                }

                if (httpMethod == null)
                {
                    httpMethod = "UNKNOWN";
                }

                GetTagValuesFromRequest(request, out host, out resourceName, out url);
                SpanContext propagatedContext = null;
                var         tracer            = Tracer.Instance;

                if (tracer.ActiveScope == null)
                {
                    try
                    {
                        // extract propagated http headers
                        if (request.TryGetPropertyValue("Headers", out IEnumerable requestHeaders))
                        {
                            var headersCollection = new DictionaryHeadersCollection();

                            foreach (object header in requestHeaders)
                            {
                                if (header.TryGetPropertyValue("Key", out string key) &&
                                    header.TryGetPropertyValue("Value", out IList <string> values))
                                {
                                    headersCollection.Add(key, values);
                                }
                            }

                            propagatedContext = SpanContextPropagator.Instance.Extract(headersCollection);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.ErrorException("Error extracting propagated HTTP headers.", ex);
                    }
                }

                _scope = tracer.StartActive(OperationName, propagatedContext);
                var span = _scope.Span;

                if (string.IsNullOrEmpty(resourceName))
                {
                    // a legacy fail safe to be removed
                    resourceName = $"{httpMethod} {controllerName}.{actionName}";
                }

                span.DecorateWebSpan(
                    resourceName: resourceName,
                    method: httpMethod,
                    host: host,
                    httpUrl: url);

                span.SetTag(Tags.AspNetController, controllerName);
                span.SetTag(Tags.AspNetAction, actionName);

                // set analytics sample rate if enabled
                var analyticsSampleRate = tracer.Settings.GetIntegrationAnalyticsSampleRate(IntegrationName, enabledWithGlobalSetting: true);
                span.SetMetric(Tags.Analytics, analyticsSampleRate);
            }
            catch (Exception) when(DisposeObject(_scope))
            {
                // unreachable code
                throw;
            }
        }
Beispiel #7
0
        private static AspNetCoreMvcContext CreateContext(object actionDescriptor, object httpContext)
        {
            var context = new AspNetCoreMvcContext();

            try
            {
                var request = httpContext.GetProperty("Request").GetValueOrDefault();

                GetTagValues(
                    actionDescriptor,
                    request,
                    out string httpMethod,
                    out string host,
                    out string resourceName,
                    out string url,
                    out string controllerName,
                    out string actionName);

                SpanContext propagatedContext = null;
                var         tracer            = Tracer.Instance;

                if (tracer.ActiveScope == null)
                {
                    try
                    {
                        // extract propagated http headers
                        var requestHeaders = request.GetProperty <IEnumerable>("Headers").GetValueOrDefault();

                        if (requestHeaders != null)
                        {
                            var headersCollection = new DictionaryHeadersCollection();

                            foreach (object header in requestHeaders)
                            {
                                var key    = header.GetProperty <string>("Key").GetValueOrDefault();
                                var values = header.GetProperty <IList <string> >("Value").GetValueOrDefault();

                                if (key != null && values != null)
                                {
                                    headersCollection.Add(key, values);
                                }
                            }

                            propagatedContext = SpanContextPropagator.Instance.Extract(headersCollection);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Error extracting propagated HTTP headers.");
                    }
                }

                var scope = tracer.StartActive(OperationName, propagatedContext);
                context.Scope = scope;
                var span = scope.Span;

                span.DecorateWebServerSpan(
                    resourceName: resourceName,
                    method: httpMethod,
                    host: host,
                    httpUrl: url);

                span.SetTag(Tags.AspNetController, controllerName);
                span.SetTag(Tags.AspNetAction, actionName);

                var analyticsSampleRate = tracer.Settings.GetIntegrationAnalyticsSampleRate(IntegrationName, enabledWithGlobalSetting: true);
                span.SetMetric(Tags.Analytics, analyticsSampleRate);
            }
            catch (Exception ex)
            {
                context.ShouldInstrument = false;
                context.Scope.Dispose();
                Log.Error(
                    ex,
                    "An exception occurred when trying to initialize a Scope for {0}",
                    nameof(AspNetCoreMvc3Integration));
                throw;
            }

            return(context);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AspNetCoreMvc2Integration"/> class.
        /// </summary>
        /// <param name="actionDescriptor">An ActionDescriptor with information about the current action.</param>
        /// <param name="httpContext">The HttpContext for the current request.</param>
        public AspNetCoreMvc2Integration(object actionDescriptor, object httpContext)
        {
            try
            {
                _httpContext = httpContext;
                string httpMethod = null;

                if (actionDescriptor.TryGetPropertyValue("ControllerName", out string controllerName))
                {
                    controllerName = controllerName?.ToLowerInvariant();
                }

                if (actionDescriptor.TryGetPropertyValue("ActionName", out string actionName))
                {
                    actionName = actionName?.ToLowerInvariant();
                }

                if (_httpContext.TryGetPropertyValue("Request", out object request) &&
                    request.TryGetPropertyValue("Method", out httpMethod))
                {
                    httpMethod = httpMethod?.ToUpperInvariant();
                }

                if (httpMethod == null)
                {
                    httpMethod = "UNKNOWN";
                }

                string url = GetDisplayUrl(request).ToLowerInvariant();

                SpanContext propagatedContext = null;

                if (Tracer.Instance.ActiveScope == null)
                {
                    try
                    {
                        // extract propagated http headers
                        if (request.TryGetPropertyValue("Headers", out IEnumerable requestHeaders))
                        {
                            var headersCollection = new DictionaryHeadersCollection();

                            foreach (object header in requestHeaders)
                            {
                                if (header.TryGetPropertyValue("Key", out string key) &&
                                    header.TryGetPropertyValue("Value", out IList <string> values))
                                {
                                    headersCollection.Add(key, values);
                                }
                            }

                            propagatedContext = SpanContextPropagator.Instance.Extract(headersCollection);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.ErrorException("Error extracting propagated HTTP headers.", ex);
                    }
                }

                _scope = Tracer.Instance.StartActive(OperationName, propagatedContext);
                var span = _scope.Span;
                span.Type         = SpanTypes.Web;
                span.ResourceName = $"{httpMethod} {controllerName}.{actionName}";
                span.SetTag(Tags.HttpMethod, httpMethod);
                span.SetTag(Tags.HttpUrl, url);
                span.SetTag(Tags.AspNetController, controllerName);
                span.SetTag(Tags.AspNetAction, actionName);
            }
            catch (Exception) when(DisposeObject(_scope))
            {
                // unreachable code
                throw;
            }
        }