Amazon EventBridge 和Amazon X-Ray - Amazon X-Ray
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

Amazon EventBridge 和Amazon X-Ray

Amazon X-Ray与 Amazon EventBridge 集成,以跟踪通过 EventBridge 传递的事件。如果使用 X-Ray SDK 检测的服务将事件发送到 EventBridge,则跟踪上下文将传播到跟踪标头。X-Ray SDK 会自动选取跟踪标头,并将其应用于任何后续工具。此连续性使用户能够跟踪、分析和调试整个下游服务,并提供更完整的系统视图。

有关更多信息,请参阅 。EventBridge X-Ray 集成中的EventBridge 用户指南

X-Ray 服务地图上查看源和目标

X-Ray服务地图显示连接源服务和目标服务的 EventBridge 事件节点,如以下示例所示:


        X-Ray 显示连接源服务和目标服务的 EventBridge 事件节点

将跟踪上下文传播到事件目标

X-Ray SDK 使 EventBridge 事件源能够将跟踪上下文传播到下游事件目标。以下特定于语言 EventBridge 示例 Lambda 示了从启用了活动跟踪

Java
package example; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SQSEvent; import com.amazonaws.xray.AWSXRay; import com.amazonaws.services.eventbridge.AmazonEventBridge; import com.amazonaws.services.eventbridge.AmazonEventBridgeClientBuilder; import com.amazonaws.services.eventbridge.model.PutEventsRequest; import com.amazonaws.services.eventbridge.model.PutEventsRequestEntry; import com.amazonaws.services.eventbridge.model.PutEventsResult; import com.amazonaws.services.eventbridge.model.PutEventsResultEntry; import com.amazonaws.xray.handlers.TracingHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.StringBuilder; import java.util.Map; import java.util.List; import java.util.Date; import java.util.Collections; /* Add the necessary dependencies for XRay: https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-xray https://mvnrepository.com/artifact/com.amazonaws/aws-xray-recorder-sdk-aws-sdk */ public class Handler implements RequestHandler<SQSEvent, String>{ private static final Logger logger = LoggerFactory.getLogger(Handler.class); /* build EventBridge client */ private static final AmazonEventBridge eventsClient = AmazonEventBridgeClientBuilder .standard() // instrument the EventBridge client with the XRay Tracing Handler. // the AWSXRay globalRecorder will retrieve the tracing-context // from the lambda function and inject it into the HTTP header. // be sure to enable 'active tracing' on the lambda function. .withRequestHandlers(new TracingHandler(AWSXRay.getGlobalRecorder())) .build(); @Override public String handleRequest(SQSEvent event, Context context) { PutEventsRequestEntry putEventsRequestEntry0 = new PutEventsRequestEntry(); putEventsRequestEntry0.setTime(new Date()); putEventsRequestEntry0.setSource("my-lambda-function"); putEventsRequestEntry0.setDetailType("my-lambda-event"); putEventsRequestEntry0.setDetail("{\"lambda-source\":\"sqs\"}"); PutEventsRequest putEventsRequest = new PutEventsRequest(); putEventsRequest.setEntries(Collections.singletonList(putEventsRequestEntry0)); // send the event(s) to EventBridge PutEventsResult putEventsResult = eventsClient.putEvents(putEventsRequest); try { logger.info("Put Events Result: {}", putEventsResult); } catch(Exception e) { e.getStackTrace(); } return "success"; } }
Python

将以下依赖项添加到 requirements.txt 文件中:

aws-xray-sdk==2.4.3
import boto3 from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.core import patch_all # apply the XRay handler to all clients. patch_all() client = boto3.client('events') def lambda_handler(event, context): response = client.put_events( Entries=[ { 'Source': 'foo', 'DetailType': 'foo', 'Detail': '{\"foo\": \"foo\"}' }, ] ) return response
Go
package main import ( "context" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-xray-sdk-go/xray" "github.com/aws/aws-sdk-go/service/eventbridge" "fmt" ) var client = eventbridge.New(session.New()) func main() { //Wrap the eventbridge client in the Amazon XRay tracer xray.AWS(client.Client) lambda.Start(handleRequest) } func handleRequest(ctx context.Context, event events.SQSEvent) (string, error) { _, err := callEventBridge(ctx) if err != nil { return "ERROR", err } return "success", nil } func callEventBridge(ctx context.Context) (string, error) { entries := make([]*eventbridge.PutEventsRequestEntry, 1) detail := "{ \"foo\": \"foo\"}" detailType := "foo" source := "foo" entries[0] = &eventbridge.PutEventsRequestEntry{ Detail: &detail, DetailType: &detailType, Source: &source, } input := &eventbridge.PutEventsInput{ Entries: entries, } // Example sending a request using the PutEventsRequest method. resp, err := client.PutEventsWithContext(ctx, input) success := "yes" if err == nil { // resp is now filled success = "no" fmt.Println(resp) } return success, err }
Node.js
const AWSXRay = require('aws-xray-sdk') //Wrap the aws-sdk client in the Amazon XRay tracer const AWS = AWSXRay.captureAWS(require('aws-sdk')) const eventBridge = new AWS.EventBridge() exports.handler = async (event) => { let myDetail = { "name": "Alice" } const myEvent = { Entries: [{ Detail: JSON.stringify({ myDetail }), DetailType: 'myDetailType', Source: 'myApplication', Time: new Date }] } // Send to EventBridge const result = await eventBridge.putEvents(myEvent).promise() // Log the result console.log('Result: ', JSON.stringify(result, null, 2)) }
C#

将以下 X-Ray 包添加到您的 C# 依赖关系:

<PackageReference Include="AWSXRayRecorder.Core" Version="2.6.2" /> <PackageReference Include="AWSXRayRecorder.Handlers.AwsSdk" Version="2.7.2" />
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon; using Amazon.Util; using Amazon.Lambda; using Amazon.Lambda.Model; using Amazon.Lambda.Core; using Amazon.EventBridge; using Amazon.EventBridge.Model; using Amazon.Lambda.SQSEvents; using Amazon.XRay.Recorder.Core; using Amazon.XRay.Recorder.Handlers.AwsSdk; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace blankCsharp { public class Function { private static AmazonEventBridgeClient eventClient; static Function() { initialize(); } static async void initialize() { //Wrap the Amazon SDK clients in the Amazon XRay tracer AWSSDKHandler.RegisterXRayForAllServices(); eventClient = new AmazonEventBridgeClient(); } public async Task<PutEventsResponse> FunctionHandler(SQSEvent invocationEvent, ILambdaContext context) { PutEventsResponse response; try { response = await callEventBridge(); } catch (AmazonLambdaException ex) { throw ex; } return response; } public static async Task<PutEventsResponse> callEventBridge() { var request = new PutEventsRequest(); var entry = new PutEventsRequestEntry(); entry.DetailType = "foo"; entry.Source = "foo"; entry.Detail = "{\"instance_id\":\"A\"}"; List<PutEventsRequestEntry> entries = new List<PutEventsRequestEntry>(); entries.Add(entry); request.Entries = entries; var response = await eventClient.PutEventsAsync(request); return response; } } }