How can I find the trace ID my lambda is under?
Asked Answered
R

1

6

I want to be able to easily find the trace ID (and segment ID) for my lambda's execution in logs.

I realise this is available on the REPORT logs that the lambda does automatically, but that logs doesn't fit my custom format for indexing and aggregation. This means it is cumbersome to get from logs about errors and such to the trace ID.

Is there a way to access the trace ID (and segment ID) from within the lambda? Looks like it's not on the context passed to the handler, and I can't see what I need in the XRay SDK. I see there are questions about changing the trace id, but I don't want to do that - just find out what it is so I can add it to all my logs.

I'm using C# .NET lambdas, although that's probably not important.

Thanks!

Rotherham answered 19/5, 2021 at 7:55 Comment(0)
C
14

There is a environment variable set in your Lambda that contains the Trace ID:

_X_AMZN_TRACE_ID

So you just need to read that environment variable in your code:

string traceId = Environment.GetEnvironmentVariable("_X_AMZN_TRACE_ID");

Source: AWS Documentation.

Carmancarmarthen answered 19/5, 2021 at 12:46 Comment(3)
Thanks Jens, had missed that - some other useful environment variables there!Rotherham
Thanks for the answer, but it should be noted that the value is the tracing header, not the trace id. When I just ran it, I got the string Root=1-62fbb4a3-6234c9a91e6aa0ce0814c996;Parent=f81b1bda242ebb9c;Sampled=1; Root is the X-Ray trace id.Lemons
@fool4jesus, the tracing header works only for a segment adjacent to AWS API Gateway. Another pairing, for example, a post-SQS segment, doesn't have this header.Tipperary

© 2022 - 2024 — McMap. All rights reserved.