아마존 EventBridge 및 AWS X-Ray - AWS X-Ray

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

아마존 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 trace 맵에는 다음 예와 같이 소스 서비스와 대상 서비스를 연결하는 EventBridge 이벤트 노드가 표시됩니다.

X-Ray는 소스 서비스와 대상 서비스를 연결하는 EventBridge 이벤트 노드를 표시합니다.

추적 컨텍스트를 이벤트 대상으로 전파하기

SDKX-Ray를 사용하면 EventBridge 이벤트 소스가 추적 컨텍스트를 다운스트림 이벤트 대상으로 전파할 수 있습니다. 다음 언어별 예제는 활성 추적이 활성화된 Lambda 함수에서의 호출을 EventBridge 보여줍니다.

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#

C# 종속성에 다음 X-Ray 패키지를 추가하세요.

<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; } } }