c# - Ocelot and AWS XRay Issue .NET 8 - Stack Overflow

I added the ocelot routes and sent the requests and so far everything is fine, the problem started when

I added the ocelot routes and sent the requests and so far everything is fine, the problem started when I wanted to add AWS X-Ray to have the traceability of everything, and it works in part, the problem I'm having is that the traces are not linked but it takes them as an individual or not related:

From what I understand from the scarce documentation is that I have to add something like this to the request:

var httpClient = new HttpClient(new HttpClientXRayTracingHandler(new HttpClientHandler()));
httpClient.GetAsync(URL);

As I understand it, it should add something like X-Amzn-Trace-Id in the request headers, but that is not happening, so I'll leave my changes here.

This is my code in the program:

const string HealthCheckEndpoint = "api/health";

var builder = WebApplication.CreateBuilder(args);

AWSXRayRecorder.InitializeInstance(builder.Configuration);

.....
var app = builder.Build();


app.UseXRay("Template-Gateway");
....
app.Run();

This is the ocelot delegate:

public class XRayTracingHandler : DelegatingHandler
{
    private readonly ILogger<XRayTracingHandler> _logger;

    public XRayTracingHandler(ILogger<XRayTracingHandler> logger)
        : base(new HttpClientXRayTracingHandler(new HttpClientHandler()))
    {
        _logger = logger;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Log the request before sending
        _logger.LogInformation("XRayTracingHandler - Sending request to {Url}", request.RequestUri);

        // Check if the X-Amzn-Trace-Id header is set
        if (request.Headers.Contains("X-Amzn-Trace-Id"))
        {
            string traceId = request.Headers.GetValues("X-Amzn-Trace-Id").FirstOrDefault() ?? "Not Found";
            _logger.LogInformation("XRayTracingHandler - X-Amzn-Trace-Id: {TraceId}", traceId);
        }
        else
        {
            _logger.LogWarning("XRayTracingHandler - X-Amzn-Trace-Id header is missing!");
        }

        var response = await base.SendAsync(request, cancellationToken);

        // Log the response status code
        _logger.LogInformation("XRayTracingHandler - Response Status Code: {StatusCode}", response.StatusCode);

        return response;
    }
}

This is the global configuration that I added in Ocelot.json:

  "GlobalConfiguration": {
     "BaseUrl": ";,
      "HttpHeadersToPass": [
          "X-Amzn-Trace-Id",
          "Authorization",
          "Content-Type"
      ]
  },
  "DelegatingHandlers": [
      "XRayTracingHandler"
  ]

Any idea what I might be doing wrong or what I'm missing?

If you need me to add any extra debugging or any AWS traces, let me know.

Thank you very much in advance

I added the ocelot routes and sent the requests and so far everything is fine, the problem started when I wanted to add AWS X-Ray to have the traceability of everything, and it works in part, the problem I'm having is that the traces are not linked but it takes them as an individual or not related:

From what I understand from the scarce documentation is that I have to add something like this to the request:

var httpClient = new HttpClient(new HttpClientXRayTracingHandler(new HttpClientHandler()));
httpClient.GetAsync(URL);

As I understand it, it should add something like X-Amzn-Trace-Id in the request headers, but that is not happening, so I'll leave my changes here.

This is my code in the program:

const string HealthCheckEndpoint = "api/health";

var builder = WebApplication.CreateBuilder(args);

AWSXRayRecorder.InitializeInstance(builder.Configuration);

.....
var app = builder.Build();


app.UseXRay("Template-Gateway");
....
app.Run();

This is the ocelot delegate:

public class XRayTracingHandler : DelegatingHandler
{
    private readonly ILogger<XRayTracingHandler> _logger;

    public XRayTracingHandler(ILogger<XRayTracingHandler> logger)
        : base(new HttpClientXRayTracingHandler(new HttpClientHandler()))
    {
        _logger = logger;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Log the request before sending
        _logger.LogInformation("XRayTracingHandler - Sending request to {Url}", request.RequestUri);

        // Check if the X-Amzn-Trace-Id header is set
        if (request.Headers.Contains("X-Amzn-Trace-Id"))
        {
            string traceId = request.Headers.GetValues("X-Amzn-Trace-Id").FirstOrDefault() ?? "Not Found";
            _logger.LogInformation("XRayTracingHandler - X-Amzn-Trace-Id: {TraceId}", traceId);
        }
        else
        {
            _logger.LogWarning("XRayTracingHandler - X-Amzn-Trace-Id header is missing!");
        }

        var response = await base.SendAsync(request, cancellationToken);

        // Log the response status code
        _logger.LogInformation("XRayTracingHandler - Response Status Code: {StatusCode}", response.StatusCode);

        return response;
    }
}

This is the global configuration that I added in Ocelot.json:

  "GlobalConfiguration": {
     "BaseUrl": "https://test.ats.mytalentaid",
      "HttpHeadersToPass": [
          "X-Amzn-Trace-Id",
          "Authorization",
          "Content-Type"
      ]
  },
  "DelegatingHandlers": [
      "XRayTracingHandler"
  ]

Any idea what I might be doing wrong or what I'm missing?

If you need me to add any extra debugging or any AWS traces, let me know.

Thank you very much in advance

Share edited Mar 8 at 18:17 Marco Nuñez asked Mar 7 at 16:32 Marco NuñezMarco Nuñez 1581 silver badge15 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

To fix it I have to create my subsegment and add the trace ID in the right format, this documentation helps me to find this missing part.

this is the final code:

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        string traceId = AWSXRayRecorder.Instance.GetEntity()?.TraceId ?? "Not Available";
        AWSXRayRecorder.Instance.BeginSubsegment($"HttpRequest-{request.RequestUri}");

        try
        {
            _logger.LogInformation("XRayTracingHandler - Sending request to {Url}", request.RequestUri);

            var entity = AWSXRayRecorder.Instance.GetEntity();
            if (entity != null)
            {
                if (!request.Headers.Contains("X-Amzn-Trace-Id"))
                {
                    var subsegmentId = entity.Id;
                    var sampled = AWSXRayRecorder.Instance.IsTracingDisabled() ? "0" : "1";
                    var traceHeader = $"Root={traceId};Parent={subsegmentId};Sampled={sampled}";

                    request.Headers.Add("X-Amzn-Trace-Id", traceHeader);
                }
            }

            var response = await base.SendAsync(request, cancellationToken);
            AWSXRayRecorder.Instance.AddAnnotation("HttpRequest", request.RequestUri?.ToString() ?? "Unknown");
            AWSXRayRecorder.Instance.AddAnnotation("HttpStatus", response.StatusCode.ToString());

            return response;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "XRayTracingHandler - Exception occurred");
            AWSXRayRecorder.Instance.AddException(ex);
            throw;
        }
        finally
        {
            AWSXRayRecorder.Instance.EndSubsegment();
        }
    }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744917875a4600949.html

相关推荐

  • c# - Ocelot and AWS XRay Issue .NET 8 - Stack Overflow

    I added the ocelot routes and sent the requests and so far everything is fine, the problem started when

    1天前
    70

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信