|
| 1 | +namespace Ocelot.Tracing.OpenTracing |
| 2 | +{ |
| 3 | + using global::OpenTracing; |
| 4 | + using global::OpenTracing.Propagation; |
| 5 | + using global::OpenTracing.Tag; |
| 6 | + using Microsoft.AspNetCore.Http; |
| 7 | + using System; |
| 8 | + using System.Collections.Generic; |
| 9 | + using System.Net.Http; |
| 10 | + using System.Threading; |
| 11 | + using System.Threading.Tasks; |
| 12 | + |
| 13 | + class OpenTracingTracer : Logging.ITracer |
| 14 | + { |
| 15 | + private readonly ITracer _tracer; |
| 16 | + |
| 17 | + public OpenTracingTracer(ITracer tracer) |
| 18 | + { |
| 19 | + _tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); |
| 20 | + } |
| 21 | + |
| 22 | + public void Event(HttpContext httpContext, string @event) |
| 23 | + { |
| 24 | + } |
| 25 | + |
| 26 | + public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, |
| 27 | + CancellationToken cancellationToken, |
| 28 | + Action<string> addTraceIdToRepo, |
| 29 | + Func<HttpRequestMessage, |
| 30 | + CancellationToken, |
| 31 | + Task<HttpResponseMessage>> baseSendAsync) |
| 32 | + { |
| 33 | + using (IScope scope = _tracer.BuildSpan(request.RequestUri.AbsoluteUri).StartActive(finishSpanOnDispose: true)) |
| 34 | + { |
| 35 | + var span = scope.Span; |
| 36 | + |
| 37 | + span.SetTag(Tags.SpanKind, Tags.SpanKindClient) |
| 38 | + .SetTag(Tags.HttpMethod, request.Method.Method) |
| 39 | + .SetTag(Tags.HttpUrl, request.RequestUri.OriginalString); |
| 40 | + |
| 41 | + addTraceIdToRepo(span.Context.SpanId); |
| 42 | + |
| 43 | + var headers = new Dictionary<string, string>(); |
| 44 | + |
| 45 | + _tracer.Inject(span.Context, BuiltinFormats.HttpHeaders, new TextMapInjectAdapter(headers)); |
| 46 | + |
| 47 | + foreach (var item in headers) |
| 48 | + { |
| 49 | + request.Headers.Add(item.Key, item.Value); |
| 50 | + } |
| 51 | + |
| 52 | + try |
| 53 | + { |
| 54 | + var response = await baseSendAsync(request, cancellationToken); |
| 55 | + |
| 56 | + span.SetTag(Tags.HttpStatus, (int)response.StatusCode); |
| 57 | + |
| 58 | + return response; |
| 59 | + } |
| 60 | + catch (HttpRequestException ex) |
| 61 | + { |
| 62 | + Tags.Error.Set(scope.Span, true); |
| 63 | + |
| 64 | + span.Log(new Dictionary<string, object>(3) |
| 65 | + { |
| 66 | + { LogFields.Event, Tags.Error.Key }, |
| 67 | + { LogFields.ErrorKind, ex.GetType().Name }, |
| 68 | + { LogFields.ErrorObject, ex } |
| 69 | + }); |
| 70 | + throw; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments