

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

# 使用 發佈 AWS Lambda 函數的 SDK 指標 AWS SDK for Java 2.x
<a name="metric-pub-impl-emf"></a>

由於 Lambda 函數通常會執行幾毫秒到幾分鐘，因此傳送指標時發生的任何延遲都會造成資料遺失`CloudWatchMetricPublisher`的風險。

`[EmfMetricLoggingPublisher](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/metrics/publishers/emf/EmfMetricLoggingPublisher.html)` 透過立即將指標寫入 [CloudWatch Embedded Metric Format (EMF)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html) 中的結構化日誌項目，提供更合適的方法。 `EmfMetricLoggingPublisher` 可在與 Amazon CloudWatch Logs AWS Lambda 和 Amazon Elastic Container Service 等內建整合的執行環境中運作。

## 設定
<a name="metric-pub-impl-emf-set-up"></a>

您必須先完成下列步驟`EmfMetricLoggingPublisher`，才能使用 啟用和使用指標。

### 步驟 1：新增必要的相依性
<a name="metric-pub-impl-emf-set-up-deps"></a>

將專案相依性 （例如，在您的 `pom.xml`或 `build.gradle` 檔案中） 設定為使用 版本 `2.30.3` 或更新版本 適用於 Java 的 AWS SDK。

在專案的相依性中，將 artifactId `emf-metric-logging-publisher` 包含版本編號 `2.30.3`或更新版本。

例如：

```
<project>
  <dependencyManagement>
   <dependencies>
      <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>bom</artifactId>
        <version>[2.30.11](https://central.sonatype.com/artifact/software.amazon.awssdk/bom)</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：設定必要的許可
<a name="metric-pub-impl-emf-set-up-perm"></a>

啟用指標發佈者使用的 IAM 身分`logs:PutLogEvents`許可，以允許適用於 Java 的 SDK 寫入 EMF 格式的日誌。

### 步驟 3：設定記錄
<a name="metric-pub-impl-emf-set-up-logger"></a>

為了確保適當的指標收集，請將您的記錄設定為輸出至 `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`檔案的詳細資訊，請參閱本指南中的[記錄主題](logging-slf4j.md)。

## 設定和使用 `EmfMetricLoggingPublisher`
<a name="metric-pub-impl-emf-use"></a>

下列 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 日誌串流。

### EMF 日誌事件的範例
<a name="emf-logged-output"></a>

例如，如果您將下列事件傳送至 GameHandler Lambda 函數，並設定記錄，如先前所示：

```
{
  "id": "23456"
}
```

函數處理事件後，您會找到兩個類似下列範例的日誌事件。第二個事件中的 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
}
```

的 [API 文件](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/metrics/publishers/emf/EmfMetricLoggingPublisher.Builder.html)`EmfMetricLoggingPublisher.Builder`會顯示您可以使用的組態選項。

您也可以為單一請求啟用 EMF 指標記錄，如 [ CloudWatchMetricPublisher 所示](metric-pub-impl-cwmp.md#enable-metrics-for-a-specific-request)。

**後續步驟：**如需長時間執行的應用程式，請參閱[從長時間執行的應用程式發佈 SDK 指標](metric-pub-impl-cwmp.md)，以進行 CloudWatch 型指標發佈。