AWS SDK for Java 2.x를 사용하여 AWS Lambda 함수에 대한 SDK 지표 게시
Lambda 함수는 일반적으로 밀리초에서 분 단위 동안 실행되므로 CloudWatchMetricPublisher에서 발생하는 지표 전송 지연으로 인해 데이터가 손실될 위험이 있습니다.
EmfMetricLoggingPublisher는 지표를 CloudWatch Embedded Metric Format(EMF)의 정형화된 로그 항목으로 즉시 작성하여 보다 적합한 접근 방식을 제공합니다. EmfMetricLoggingPublisher는 AWS Lambda 및 Amazon Elastic Container Service등 Amazon CloudWatch Logs와의 통합이 내장된 실행 환경에서 작동합니다.
설정
EmfMetricLoggingPublisher를 통해 지표를 사용 설정하고 사용하려면 먼저 다음 단계를 완료해야 합니다.
1단계: 필수 종속성 추가
AWS SDK for Java 버전 2.30.3 또는 그 이상의 버전을 사용하도록 프로젝트 종속성(예: pom.xml 또는 build.gradle 파일)을 구성하세요.
프로젝트 종속 항목에 버전 번호 2.30.3 이상의 emf-metric-logging-publisher artifactId를 포함해야 합니다.
예:
<project> <dependencyManagement> <dependencies> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>bom</artifactId> <version>2.30.11</version> <!-- Navigate the link to see the latest version. --> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>emf-metric-logging-publisher</artifactId> </dependency> </dependencies> </project>
2단계: 필수 권한 구성
SDK for Java에서 지표 게시자를 사용하여 IAM ID에 대한 logs:PutLogEvents 권한을 사용 설정해 EMF 형식 로그를 작성합니다.
3단계: 로깅 설정
적절한 지표 수집을 확보하려면 INFO 수준 이하(예: DEBUG)에서 콘솔에 출력하도록 로깅을 구성합니다. log4j2.xml 파일의 경우:
<Loggers> <Root level="WARN"> <AppenderRef ref="ConsoleAppender"/> </Root> <Logger name="software.amazon.awssdk.metrics.publishers.emf.EmfMetricLoggingPublisher" level="INFO" /> </Loggers>
log4j2.xml 파일 설정 방법에 대한 자세한 내용은 이 가이드의 로깅 주제를 참조하세요.
EmfMetricLoggingPublisher 구성 및 사용
다음 Lambda 함수 클래스는 먼저 EmfMetricLoggingPublisher 인스턴스를 만들고 구성한 다음 Amazon DynamoDB 서비스 클라이언트와 함께 사용합니다.
public class GameIdHandler implements RequestHandler<Map<String, String>, String> { private final EmfMetricLoggingPublisher emfPublisher; private final DynamoDbClient dynamoDb; public GameIdHandler() { // Build the publisher. this.emfPublisher = EmfMetricLoggingPublisher.builder() .namespace("namespace") .dimensions(CoreMetric.SERVICE_ID, CoreMetric.OPERATION_NAME) .build(); // Add the publisher to the client. this.dynamoDb = DynamoDbClient.builder() .overrideConfiguration(c -> c.addMetricPublisher(emfPublisher)) .region(Region.of(System.getenv("AWS_REGION"))) .build(); } @Override public String handleRequest(Map<String, String> event, Context context) { Map<String, AttributeValue> gameItem = new HashMap<>(); gameItem.put("gameId", AttributeValue.builder().s(event.get("id")).build()); PutItemRequest putItemRequest = PutItemRequest.builder() .tableName("games") .item(gameItem) .build(); dynamoDb.putItem(putItemRequest); return "Request handled"; } }
DynamoDB 클라이언트는 putItem 메서드를 실행할 경우 지표를 EMF 형식의 CloudWatch 로그 스트림에 자동으로 게시합니다.
예를 들어 다음과 같이 구성된 로깅을 사용하여 GameHandler Lambda 함수에 다음 이벤트를 전송하는 경우입니다.
{ "id": "23456" }
함수에서 이벤트를 처리한 후 다음 예제와 유사한 2개의 로그 이벤트를 찾습니다. 두 번째 이벤트의 JSON 객체에는 DynamoDB에 대한 PutItem 작업의 Java SDK 지표 데이터가 포함됩니다.
CloudWatch는 EMF 형식의 로그 이벤트를 수신하면 정형화된 JSON을 자동으로 구문 분석하여 지표 데이터를 추출합니다. 그런 다음 CloudWatch는 원본 로그 항목을 CloudWatch Logs에 저장하는 동안 해당 지표를 만듭니다.
2025-07-11 15:58:30 [main] INFO org.example.GameIdHandler:39 - Received map: {id=23456} 2025-07-11 15:58:34 [main] INFO software.amazon.awssdk.metrics.publishers.emf.EmfMetricLoggingPublisher:43 - { "_aws": { "Timestamp": 1752249513975, "LogGroupName": "/aws/lambda/GameId", "CloudWatchMetrics": [ { "Namespace": "namespace", "Dimensions": [ [ "OperationName", "ServiceId" ] ], "Metrics": [ { "Name": "AvailableConcurrency" }, { "Name": "PendingConcurrencyAcquires" }, { "Name": "ServiceCallDuration", "Unit": "Milliseconds" }, { "Name": "EndpointResolveDuration", "Unit": "Milliseconds" }, { "Name": "MaxConcurrency" }, { "Name": "BackoffDelayDuration", "Unit": "Milliseconds" }, { "Name": "MarshallingDuration", "Unit": "Milliseconds" }, { "Name": "LeasedConcurrency" }, { "Name": "SigningDuration", "Unit": "Milliseconds" }, { "Name": "ConcurrencyAcquireDuration", "Unit": "Milliseconds" }, { "Name": "ApiCallSuccessful" }, { "Name": "RetryCount" }, { "Name": "UnmarshallingDuration", "Unit": "Milliseconds" }, { "Name": "ApiCallDuration", "Unit": "Milliseconds" }, { "Name": "CredentialsFetchDuration", "Unit": "Milliseconds" } ] } ] }, "AvailableConcurrency": 0, "PendingConcurrencyAcquires": 0, "OperationName": "PutItem", "ServiceCallDuration": 1339, "EndpointResolveDuration": 81, "MaxConcurrency": 50, "BackoffDelayDuration": 0, "ServiceId": "DynamoDB", "MarshallingDuration": 181, "LeasedConcurrency": 1, "SigningDuration": 184, "ConcurrencyAcquireDuration": 83, "ApiCallSuccessful": 1, "RetryCount": 0, "UnmarshallingDuration": 85, "ApiCallDuration": 1880, "CredentialsFetchDuration": 138 }
EmfMetricLoggingPublisher.Builder의 API 설명서
또한 CloudWatchMetricPublisher에 표시된 대로 단일 요청에 대해 EMF 지표 로깅을 사용할 수 있습니다.
다음 단계: 장기 실행 애플리케이션의 경우 CloudWatch 기반 지표 게시를 위해 장기 실행 애플리케이션의 SDK 지표 게시를 참조하세요.