

# 为 S3 Storage Lens 存储统计管理工具启用 CloudWatch 发布
<a name="storage-lens-cloudwatch-enable-publish-option"></a>

您可以将 S3 Storage Lens 存储统计管理工具指标发布到 Amazon CloudWatch，以便在 [CloudWatch 控制面板](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)中创建运营状况的统一视图。您还可以使用 CloudWatch 功能（如告警和触发操作、指标数学和异常检测）来监控 S3 Storage Lens 存储统计管理工具指标并采取措施。此外，CloudWatch API 操作使应用程序（包括第三方提供商）能够访问 S3 Storage Lens 存储统计管理工具指标。有关 CloudWatch 功能的更多信息，请参阅 [Amazon CloudWatch 用户指南](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html)。

S3 Storage Lens 存储统计管理工具指标在拥有 S3 Storage Lens 存储统计管理工具配置的账户中发布到 CloudWatch。在高级指标中启用 CloudWatch 发布选项后，您可以在 CloudWatch 中按配置 ID、账户、存储桶（仅适用于存储桶级指标）、区域和存储类别，访问账户级别和存储桶级别的指标。前缀级别的指标在 CloudWatch 中不可用。

您可以使用 Amazon S3 控制台、REST API、AWS CLI 和 AWS SDK 针对新的或当前控制面板配置启用 CloudWatch 支持。CloudWatch 发布选项可用于升级到 S3 Storage Lens 存储统计管理工具高级指标和建议。有关 S3 Storage Lens 存储统计管理工具高级指标和建议定价，请参阅 [Amazon S3 定价](https://aws.amazon.com/s3/pricing/)。不会收取其他 CloudWatch 指标发布费用；但是，其他 CloudWatch 费用（例如控制面板、告警和 API 调用）确实适用。

要启用 S3 Storage Lens 存储统计管理工具指标的 CloudWatch 发布选项，请参阅以下主题。

**注意**  
S3 Storage Lens 存储统计管理工具指标是每日指标，每天发布到 CloudWatch 一次。当您在 CloudWatch 中查询 S3 Storage Lens 存储统计管理工具指标时，查询的期限必须为 1 天（86400 秒）。在您的每日 S3 Storage Lens 指标显示在 Amazon S3 控制台的 S3 Storage Lens 存储统计管理工具控制面板中后，这些指标可能需要几个小时才能显示在 CloudWatch 中。当您首次为 S3 Storage Lens 存储统计管理工具指标启用 CloudWatch 发布选项时，您的指标最多可能需要 24 小时才能将指标发布到 CloudWatch。  
目前，S3 Storage Lens 存储统计管理工具指标无法通过 CloudWatch 流使用。

## 使用 S3 控制台
<a name="storage-lens-cloudwatch-enable-publish-console"></a>

更新 S3 Storage Lens 存储统计管理工具控制面板时，无法更改控制面板名称或主区域。您也不能更改原定设置控制面板的范围，其范围限于整个账户的存储。

**更新 S3 Storage Lens 存储统计管理工具控制面板以启用 CloudWatch 发布**

1. 登录到 AWS 管理控制台，然后通过以下网址打开 Amazon S3 控制台：[https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/)。

1. 在导航窗格中，依次选择 **S3 Storage Lens** 和 **Dashboards**（控制面板）。

1. 请选择要编辑的控制面板，然后选择 **Edit**（编辑）。

1. 在 **Metrics selection**（指标选择）下方，请选择 **Advanced metrics and recommendations**（高级指标和建议）。

   高级指标和建议可额外收费。高级指标和建议包括 15 个月的数据查询期、在前缀级别聚合的使用情况指标、按桶聚合的活动指标、CloudWatch 发布选项，以及帮助您优化存储成本和应用数据保护最佳做法的上下文建议。有关更多信息，请参阅 [Amazon S3 定价](https://aws.amazon.com/s3/pricing/)。

1. 在 **Select Advanced metrics and recommendations features**（选择高级指标和推荐功能）下方，选择 **CloudWatch publishing**（CloudWatch 发布）。
**重要**  
如果您的配置启用了使用情况指标的前缀聚合，则前缀级指标将不会发布到 CloudWatch。只有桶、账户和企业级 S3 Storage Lens 存储统计管理工具指标才会发布到 CloudWatch。

1. 选择**保存更改**。

**要创建启用 CloudWatch 支持的新 S3 Storage Lens 存储统计管理工具控制面板**

1. 登录到 AWS 管理控制台，然后通过以下网址打开 Amazon S3 控制台：[https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/)。

1. 在左侧导航窗格中，依次选择 **Storage Lens** 和 **Dashboards**（控制面板）。

1. 请选择**创建控制面板**。

1. 在 **General**（常规）下，定义以下配置选项：

   1. 对于 **Dashboard name**（控制面板名称），输入您的控制面板名称。

      控制面板名称必须少于 65 个字符，且不得包含特殊字符或空格。创建控制面板后，您无法更改此控制面板名称。

   1. 为控制面板选择 **Home Region**（主区域）。

      此控制面板范围内所有包含的所有区域的指标，都集中存储在此指定的主区域中。在 CloudWatch 中，S3 Storage Lens 存储统计管理工具指标也可在主区域提供。创建控制面板后，您无法更改主区域。

1. （可选）要添加标签，请选择 **Add tag **（添加标签），然后输入标签 **Key**（密钥）和 **Value**（值）。
**注意**  
您最多可以在控制面板配置中添加 50 个标签。

1. 定义配置的范围：

   1. 如果您正在创建组织级配置，请选择要包含在配置中的账户：**Include all accounts in your configuration**（在配置中包括所有账户）或者 **Limit the scope to your signed-in account**（将范围限制为您的登录账户）。
**注意**  
当您创建包含所有账户的组织级配置时，您只能包括或排除区域，而不能包括或排除桶。

   1. 通过执行以下操作，选择您希望 S3 Storage Lens 存储统计管理工具在控制面板配置中包括的区域和桶：
      + 要包含所有区域，请选择 **Include Regions and buckets**（包含区域和桶）。
      + 要包含特定的区域，请清除 **Include all Regions**（包含所有区域）。在 **Choose Regions to include**（选择要包含的区域）下方，请选择想要 S3 Storage Lens 存储统计管理工具包含在控制面板中的区域。
      + 要包含特定桶，请清除 **Include all buckets**（包含所有桶）。在 **Choose buckets to include**（选择要包含的桶）下方，请选择想要 S3 Storage Lens 存储统计管理工具包含在控制面板中的桶。
**注意**  
您最多可以选择 50 个桶。

1. 对于 **Metrics selection**（指标选择），请选择 **Advanced metrics and recommendations**（高级指标和建议）。

   有关高级指标和建议定价的资讯，请参阅 [Amazon S3 pricing](https://aws.amazon.com/s3/pricing/)（Amazon S3 定价）。

1. 在 **Advanced metrics and recommendations features**（高级指标和建议功能）下方，选择您要启用的选项：
   + **Advanced metrics（高级指标** 
   + **CloudWatch publishing（CloudWatch 发布**
**重要**  
如果您为 S3 Storage Lens 存储统计管理工具配置启用了前缀聚合，那么前缀级别的指标将不会发布到 CloudWatch。只有桶、账户和企业级 S3 Storage Lens 存储统计管理工具指标才会发布到 CloudWatch。
   + **Prefix aggregation（前缀聚合**
**注意**  
有关高级指标和建议功能的更多信息，请参阅[指标选择](storage_lens_basics_metrics_recommendations.md#storage_lens_basics_metrics_selection)。

1. 如果您启用了 **Advanced metrics**（高级指标），请选择要在 S3 Storage Lens 存储统计管理工具控制面板中显示的 **Advanced metrics categories**（高级指标类别）：
   + **活动指标**
   + **Detailed status code metrics（详细的状态代码指标**
   + **Advanced cost optimization metrics（高级成本优化指标**
   + **Advanced data protection metrics（高级数据保护指标**

   有关指标类别的更多信息，请参阅[指标类别](storage_lens_basics_metrics_recommendations.md#storage_lens_basics_metrics_types)。要获得指标的完整列表，请参阅 [Amazon S3 Storage Lens 存储统计管理工具指标词汇表](storage_lens_metrics_glossary.md)。

1. （可选）配置您的指标导出。

   有关如何配置指标导出的更多信息，请参阅步骤 [使用 S3 控制台](storage_lens_creating_dashboard.md#storage_lens_console_creating)。

1. 请选择**创建控制面板**。

## 使用 AWS CLI
<a name="storage-lens-cloudwatch-enable-publish-cli"></a>

以下 AWS CLI 示例将通过使用 S3 Storage Lens 存储统计管理工具组织级高级指标和建议配置启用 CloudWatch 发布选项。要使用此示例，请将 `user input placeholders` 替换为您自己的信息。

```
aws s3control put-storage-lens-configuration --account-id=555555555555 --config-id=your-configuration-id --region=us-east-1 --storage-lens-configuration=file://./config.json

config.json
{
  "Id": "SampleS3StorageLensConfiguration",
  "AwsOrg": {
    "Arn": "arn:aws:organizations::123456789012:organization/o-abcdefgh"
  },
  "AccountLevel": {
    "ActivityMetrics": {
      "IsEnabled":true
    },
    "AdvancedCostOptimizationMetrics": {
      "IsEnabled":true
    },
    "AdvancedDataProtectionMetrics": {
      "IsEnabled":true
    },
    "DetailedStatusCodesMetrics": {
      "IsEnabled":true
    },
    "BucketLevel": {
      "ActivityMetrics": {
        "IsEnabled":true
      },
      "AdvancedCostOptimizationMetrics": {
        "IsEnabled":true
      },
      "DetailedStatusCodesMetrics": {
        "IsEnabled":true
      },
      "PrefixLevel":{
        "StorageMetrics":{
          "IsEnabled":true,
          "SelectionCriteria":{
            "MaxDepth":5,
            "MinStorageBytesPercentage":1.25,
            "Delimiter":"/"
          }
        }
      }
    }
  },
  "Exclude": {
    "Regions": [
      "eu-west-1"
    ],
    "Buckets": [
      "arn:aws:s3:::amzn-s3-demo-source-bucket "
    ]
  },
  "IsEnabled": true,
  "DataExport": {
    "S3BucketDestination": {
      "OutputSchemaVersion": "V_1",
      "Format": "CSV",
      "AccountId": "111122223333",
      "Arn": "arn:aws:s3:::amzn-s3-demo-destination-bucket",
      "Prefix": "prefix-for-your-export-destination",
      "Encryption": {
        "SSES3": {}
      }
    },
    "CloudWatchMetrics": {
      "IsEnabled": true
    }
  }
}
```

## 使用适用于 Java 的 AWS 开发工具包
<a name="storage-lens-cloudwatch-enable-publish-sdk"></a>

```
package aws.example.s3control;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3control.AWSS3Control;
import com.amazonaws.services.s3control.AWSS3ControlClient;
import com.amazonaws.services.s3control.model.AccountLevel;
import com.amazonaws.services.s3control.model.ActivityMetrics;
import com.amazonaws.services.s3control.model.BucketLevel;
import com.amazonaws.services.s3control.model.CloudWatchMetrics;
import com.amazonaws.services.s3control.model.Format;
import com.amazonaws.services.s3control.model.Include;
import com.amazonaws.services.s3control.model.OutputSchemaVersion;
import com.amazonaws.services.s3control.model.PrefixLevel;
import com.amazonaws.services.s3control.model.PrefixLevelStorageMetrics;
import com.amazonaws.services.s3control.model.PutStorageLensConfigurationRequest;
import com.amazonaws.services.s3control.model.S3BucketDestination;
import com.amazonaws.services.s3control.model.SSES3;
import com.amazonaws.services.s3control.model.SelectionCriteria;
import com.amazonaws.services.s3control.model.StorageLensAwsOrg;
import com.amazonaws.services.s3control.model.StorageLensConfiguration;
import com.amazonaws.services.s3control.model.StorageLensDataExport;
import com.amazonaws.services.s3control.model.StorageLensDataExportEncryption;
import com.amazonaws.services.s3control.model.StorageLensTag;

import java.util.Arrays;
import java.util.List;

import static com.amazonaws.regions.Regions.US_WEST_2;

public class CreateAndUpdateDashboard {

    public static void main(String[] args) {
        String configurationId = "ConfigurationId";
        String sourceAccountId = "Source Account ID";
        String exportAccountId = "Destination Account ID";
        String exportBucketArn = "arn:aws:s3:::amzn-s3-demo-destination-bucket"; // The destination bucket for your metrics export must be in the same Region as your S3 Storage Lens configuration.
        String awsOrgARN = "arn:aws:organizations::123456789012:organization/o-abcdefgh";
        Format exportFormat = Format.CSV;

        try {
            SelectionCriteria selectionCriteria = new SelectionCriteria()
                    .withDelimiter("/")
                    .withMaxDepth(5)
                    .withMinStorageBytesPercentage(10.0);
            PrefixLevelStorageMetrics prefixStorageMetrics = new PrefixLevelStorageMetrics()
                    .withIsEnabled(true)
                    .withSelectionCriteria(selectionCriteria);
            BucketLevel bucketLevel = new BucketLevel()
                    .withActivityMetrics(new ActivityMetrics().withIsEnabled(true))
                    .withAdvancedCostOptimizationMetrics(new AdvancedCostOptimizationMetrics().withIsEnabled(true))
                    .withAdvancedDataProtectionMetrics(new AdvancedDataProtectionMetrics().withIsEnabled(true))
                    .withDetailedStatusCodesMetrics(new DetailedStatusCodesMetrics().withIsEnabled(true))
                    .withPrefixLevel(new PrefixLevel().withStorageMetrics(prefixStorageMetrics));
            AccountLevel accountLevel = new AccountLevel()
                    .withActivityMetrics(new ActivityMetrics().withIsEnabled(true))
                    .withAdvancedCostOptimizationMetrics(new AdvancedCostOptimizationMetrics().withIsEnabled(true))
                    .withAdvancedDataProtectionMetrics(new AdvancedDataProtectionMetrics().withIsEnabled(true))
                    .withDetailedStatusCodesMetrics(new DetailedStatusCodesMetrics().withIsEnabled(true))
                    .withBucketLevel(bucketLevel);

            Include include = new Include()
                    .withBuckets(Arrays.asList("arn:aws:s3:::amzn-s3-demo-bucket"))
                    .withRegions(Arrays.asList("us-west-2"));

            StorageLensDataExportEncryption exportEncryption = new StorageLensDataExportEncryption()
                    .withSSES3(new SSES3());
            S3BucketDestination s3BucketDestination = new S3BucketDestination()
                    .withAccountId(exportAccountId)
                    .withArn(exportBucketArn)
                    .withEncryption(exportEncryption)
                    .withFormat(exportFormat)
                    .withOutputSchemaVersion(OutputSchemaVersion.V_1)
                    .withPrefix("Prefix");
            CloudWatchMetrics cloudWatchMetrics = new CloudWatchMetrics()
                    .withIsEnabled(true);
            StorageLensDataExport dataExport = new StorageLensDataExport()
                    .withCloudWatchMetrics(cloudWatchMetrics)
                    .withS3BucketDestination(s3BucketDestination);

            StorageLensAwsOrg awsOrg = new StorageLensAwsOrg()
                    .withArn(awsOrgARN);

            StorageLensConfiguration configuration = new StorageLensConfiguration()
                    .withId(configurationId)
                    .withAccountLevel(accountLevel)
                    .withInclude(include)
                    .withDataExport(dataExport)
                    .withAwsOrg(awsOrg)
                    .withIsEnabled(true);

            List<StorageLensTag> tags = Arrays.asList(
                    new StorageLensTag().withKey("key-1").withValue("value-1"),
                    new StorageLensTag().withKey("key-2").withValue("value-2")
            );

            AWSS3Control s3ControlClient = AWSS3ControlClient.builder()
                    .withCredentials(new ProfileCredentialsProvider())
                    .withRegion(US_WEST_2)
                    .build();

            s3ControlClient.putStorageLensConfiguration(new PutStorageLensConfigurationRequest()
                    .withAccountId(sourceAccountId)
                    .withConfigId(configurationId)
                    .withStorageLensConfiguration(configuration)
                    .withTags(tags)
            );
        } catch (AmazonServiceException e) {
            // The call was transmitted successfully, but Amazon S3 couldn't process
            // it and returned an error response.
            e.printStackTrace();
        } catch (SdkClientException e) {
            // Amazon S3 couldn't be contacted for a response, or the client
            // couldn't parse the response from Amazon S3.
            e.printStackTrace();
        }
    }
}
```

## 使用 REST API
<a name="storage-lens-cloudwatch-enable-publish-api"></a>

要使用 Amazon S3 REST API 启用 CloudWatch 发布选项，您可以使用 [https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_PutStorageLensConfiguration.html](https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_PutStorageLensConfiguration.html)。

**后续步骤**  
启用 CloudWatch 发布选项后，您可以在 CloudWatch 中访问 S3 Storage Lens 存储统计管理工具指标。您还可以利用 CloudWatch 功能在 CloudWatch 中监控和分析 S3 Storage Lens 存储统计管理工具数据。有关更多信息，请参阅以下主题：
+ [S3 Storage Lens 存储统计管理工具指标和维度](storage-lens-cloudwatch-metrics-dimensions.md)
+ [在 CloudWatch 中结合使用 S3 Storage Lens 存储统计管理工具指标](storage-lens-cloudwatch-monitoring-cloudwatch.md)