Amazon EventBridge 和 AWS X-Ray - AWS X-Ray

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

Amazon EventBridge 和 AWS X-Ray

AWS X-Ray 與 Amazon 集成 EventBridge 以跟踪傳遞的事件 EventBridge。如果使用 X-Ray 檢測的服務將事件傳SDK送至 EventBridge,追蹤前後關聯會傳播至追蹤標頭內的下游事件目標。X-Ray SDK 會自動拾取追蹤標頭,並將其套用至任何後續儀器。這種連續性可讓使用者在整個下游服務中追蹤、分析和偵錯,並提供更完整的系統檢視。

若要取得更多資訊,請參閱EventBridge 使用指南中的 EventBridge X-Ray 整合

檢視 X-Ray 服務圖上的來源和目標

X-Ray 追蹤對映會顯示連接來源和目標服務的 EventBridge 事件節點,如下列範例所示:

X-Ray 顯示連接來源和目標服務的 EventBridge 事件節點

將追蹤內容傳播至事件目標

X-Ray SDK 可讓 EventBridge 事件來源將追蹤環境傳播至下游事件目標。下列語言特定範例示範 EventBridge 從啟用主動追蹤的 Lambda 函數呼叫:

Java

為 X-Ray 添加必要的依賴關係:

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 AWS 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 AWS 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 AWS SDK clients in the AWS 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; } } }