AWS X-Ray GoLang Lambda 到 lambda 跟踪并显示在服务地图中

AWS X-Ray GoLang Lambda to lambda tracing and displayed in the service map

我有 API 网关,它调用 Lamdba 函数 1 并在 Go 中调用 lambda 函数 2。我想在服务地图中看到这两个功能。

到目前为止,我能够做到这一点的唯一方法是创建一个自定义细分,例如称为 "parent" 并从该上下文创建一个子细分,例如称为 "child"。然后使用 client.InvokeWithContext 调用传递 "child" 段上下文的函数 2。

sess := session.Must(session.NewSession())
client := lambda.New(sess, &aws.Config{Region: aws.String(region)})

xray.Configure(xray.Config{LogLevel: "trace"})
xray.AWS(client.Client)

ctx, seg := xray.BeginSegment(context.Background(), "Parent")
ctx, subseg := xray.BeginSubsegment(ctx, "Child")
result, _ := client.InvokeWithContext(ctx, 
    lambda.InvokeInput{FunctionName: aws.String(functionName), Payload: nil})
subseg.Close(nil)   
seg.Close(nil)

问题是这会在服务映射中创建跟踪父级 -> 子级,但也有功能 1。

请问在服务地图上加入这两个功能的最佳方式是什么? 笔记。我有超过 2 个我想在服务地图上看到链接,以向我展示我通过 lambda 的整个流程。

请帮忙。

谢谢 瑞克

除非您想添加 annotation/metadata.

,否则您不需要为 "child" 调用添加子分段

API 网关将一个名为 X-Amzn-Trace-Id 的跟踪 ID 添加到传入请求的 header 中,X-ray 接收该 ID。如果您在从 lambda 1 到 lambda 2 的调用中转发该跟踪 ID,则 X-ray 将在概览中用从 lambda 1 到 lambda 2 的箭头直观地表示调用,并在查看时包括 lambda 2 的跟踪详细信息跟踪 lambda 1.

的详细信息

只要您通过调用链转发顶部跟踪 ID,X-ray 将使用节点和箭头正确地可视化从一个服务到另一个服务的调用链。

来自https://aws.amazon.com/xray/faqs/

Q: What is a trace?

An X-Ray trace is a set of data points that share the same trace ID. For example, when a client makes a request to your application, it is assigned a unique trace ID. As the request makes its way through services in your application, the services relay information regarding the request back to X-Ray using this unique trace ID. The piece of information relayed by each service in your application to X-Ray is a segment, and a trace is a collection of segments.

https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-tracingheader

https://docs.aws.amazon.com/xray/latest/devguide/xray-services-apigateway.html

Go and Lambda boilerplate app 演示 X-Ray 服务地图上的 Lambda 到 Lambda 跟踪:

https://github.com/nzoschke/gofaas/blob/master/worker.go

Resulting X-Ray Service Map

WorkCreateFunction(函数 1)是一个 API 网关处理函数。它通过 Lambda.InvokeWithContext 调用调用 WorkerFunction(函数 2)。

诀窍是在进行 Lambda API 调用之前使用 xray 检测 Lambda API 客户端:

// Lambda is an xray instrumented Lambda client
func Lambda() *lambda.Lambda {
    c := lambda.New(sess)
    xray.AWS(c.Client)
    return c
}

out, err := Lambda().InvokeWithContext(ctx, &lambda.InvokeInput{
    FunctionName:   aws.String(os.Getenv("WORKER_FUNCTION_NAME")),
    InvocationType: aws.String("Event"), // async
})
if err != nil {
    return responseEmpty, errors.WithStack(err)
}

aws-xray-sdk-go 将函数 1 中的 X-Amzn-Trace-Id header 复制到函数 2 的 Lambda API 请求中:

https://github.com/aws/aws-xray-sdk-go/blob/master/xray/aws.go#L56

如果这不起作用,请尝试更新到最新的 aws-xray-sdk-go