protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // skip execution when no provider is registered if (_provider == null) { return(base.SendAsync(request, cancellationToken)); } // extract correlation id from http headers var correlationId = _provider.GetCorrelationId(); if (string.IsNullOrWhiteSpace(correlationId)) { return(base.SendAsync(request, cancellationToken)); } // add correlation id as query parameter var requestUrl = request.RequestUri?.AbsoluteUri ?? throw new InvalidOperationException(); request.RequestUri = new Uri(QueryHelpers.AddQueryString(requestUrl, CorrelationIdQueryParameter, correlationId)); return(base.SendAsync(request, cancellationToken)); }
public async Task Invoke(HttpContext context, ICorrelationIdProvider correlationIdProvider) { if (context == null) { throw new System.ArgumentNullException(nameof(context)); } try { var loggerState = new LoggerState { [correlationIdProvider.CorrelationIdKey] = correlationIdProvider.GetCorrelationId() //Add any number of properties to be logged under a single scope }; using (_logger.BeginScope(loggerState)) { await _next(context); } } //To make sure that we don't loose the scope in case of an unexpected error catch (Exception ex) when(LogOnUnexpectedError(ex)) { } }
public ApiClientProxy(ApiOptions options, ILogger logger, ICorrelationIdProvider correlationIdProvider) { Guard.ArgumentNotNull(options, nameof(options)); Guard.IsNullOrWhiteSpace(options.ApiEndpoint, nameof(options.ApiEndpoint)); Guard.IsNullOrWhiteSpace(options.ApiKey, nameof(options.ApiKey)); Guard.ArgumentNotNull(logger, nameof(logger)); Guard.ArgumentNotNull(correlationIdProvider, nameof(correlationIdProvider)); _correlationIdProvider = correlationIdProvider; _httpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }); string baseAddress = options.ApiEndpoint; if (!baseAddress.EndsWith("/", StringComparison.CurrentCulture)) { baseAddress = $"{baseAddress}/"; } _httpClient.BaseAddress = new Uri(baseAddress, UriKind.Absolute); _httpClient.DefaultRequestHeaders?.Add(OcpApimSubscriptionKey, options.ApiKey); _httpClient.DefaultRequestHeaders?.Add(SfaCorellationId, _correlationIdProvider.GetCorrelationId()); _httpClient.DefaultRequestHeaders?.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders?.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); _httpClient.DefaultRequestHeaders?.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate")); _logger = logger; }
public async Task Invoke(HttpContext context) { var correlationId = _correlationIdProvider.GetCorrelationId(); using (_logger.BeginScope(("correlation_id", correlationId))) { context.TraceIdentifier = correlationId; context.Request.Headers.Add("correlationId", correlationId); await _next(context); } }
/// <summary> /// Enrich LogEvent message with provided CorrelationId or generate a new one for this HTTP request. /// </summary> /// <param name="logEvent">>Log Event</param> /// <param name="propertyFactory">Serilog Property Factory</param> public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { if (logEvent == null) { throw new ArgumentNullException("logEvent"); } if (propertyFactory == null) { throw new ArgumentNullException("propertyFactory"); } string value = _correlationIdLookup.GetCorrelationId(); if (!string.IsNullOrWhiteSpace(value)) { LogEventProperty property = propertyFactory.CreateProperty("CorrelationId", value, false); logEvent.AddOrUpdateProperty(property); } }
public Task Invoke(HttpContext context, ICorrelationIdProvider correlationIdProvider) { if (correlationIdProvider == null) { throw new Exception("No correlationId provider found. Did you setup Narato.Correlations correctly?"); } var correlationId = correlationIdProvider.GetCorrelationId().ToString(); if (!context.Response.Headers.ContainsKey(CorrelationIdProvider.CORRELATION_ID_HEADER_NAME)) { context .Response .Headers .Add(CorrelationIdProvider.CORRELATION_ID_HEADER_NAME, correlationId); } return(_next(context)); }
// Override this method if you use anything other than IValidationException<string> // first check if it is your IValidationException, and then call base.Map(ex) public virtual IActionResult Map(Exception ex) { foreach (var hook in _mapperHooks) { var result = hook.Map(ex); if (result != null) { return(result); } } var absolutePath = _httpContextAccessor.HttpContext.Request.Path; if (ex is IValidationException <string> ) { var typedEx = ex as IValidationException <string>; var response = new ErrorResponse(typedEx.ValidationMessages.ToFeedbackItems().ToList(), absolutePath, 400); response.Identifier = _correlationIdProvider.GetCorrelationId(); response.Title = "Validation failed."; return(new BadRequestObjectResult(response)); } if (ex is EntityNotFoundException) { var typedEx = ex as EntityNotFoundException; if (string.IsNullOrEmpty(typedEx.Message)) { return(new NotFoundResult()); } var response = new ErrorResponse(new FeedbackItem { Description = typedEx.Message, Type = FeedbackType.Error }, absolutePath, 404); response.Identifier = _correlationIdProvider.GetCorrelationId(); response.Title = "Entity could not be found."; return(new NotFoundObjectResult(response)); } if (ex is UnauthorizedException) { return(new UnauthorizedResult()); } if (ex is ForbiddenException) { return(new ForbidResult()); } if (ex is ExceptionWithFeedback) { var typedEx = ex as ExceptionWithFeedback; var response = new ErrorResponse(typedEx.Message.ToFeedbackItem(FeedbackType.Error), absolutePath, 500); response.Identifier = _correlationIdProvider.GetCorrelationId(); response.Title = "Unexpected internal server error."; return(new InternalServerObjectResult(response)); } _logger.LogTrace($"Exception of type {ex.GetType().Name} was mapped by the catch all mapper."); var message = "Something went wrong. Contact support and give them the identifier found below."; // if development ==> expose exception message if (_hostingEnvironment.IsDevelopment()) { message = ex.Message; } // catch all (just Exception) var catchAllResponse = new ErrorResponse(message.ToFeedbackItem(FeedbackType.Error), absolutePath, 500); catchAllResponse.Identifier = _correlationIdProvider.GetCorrelationId(); catchAllResponse.Title = "Unexpected internal server error."; return(new InternalServerObjectResult(catchAllResponse)); }
protected override Task <HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (!request.Headers.Contains(CorrelationIdProvider.CORRELATION_ID_HEADER_NAME)) { request.Headers.Add(CorrelationIdProvider.CORRELATION_ID_HEADER_NAME, _correlationIdProvider.GetCorrelationId().ToString()); } return(base.SendAsync(request, cancellationToken)); }
public ActionResult <string> WithCorrelationId([FromHeader(Name = "X-Correlation-Id")] string correlationId) { return($"correlationId:{_correlationIdProvider.GetCorrelationId()}"); }
public ActionResult <string> WithCorrelationId([FromHeader(Name = CorrelationProvider.DefaultCorrelationIdHeaderKey)] string correlationId) { return($"correlationId:{_correlationIdProvider.GetCorrelationId()}"); }