

# 启用 Amazon S3 服务器访问日志记录
<a name="enable-server-access-logging"></a>

服务器访问日志记录详细地记录对 Amazon S3 存储桶提出的各种请求。对于许多应用程序而言，服务器访问日志很有用。例如，访问日志信息可能在安全和访问权限审核方面很有用。此信息还有助于您了解客户群以及您的 Amazon S3 账单。

默认情况下，Amazon S3 不会收集服务器访问日志。在您启用日志记录后，Amazon S3 会将源存储桶的访问日志传输到您选择的目的地存储桶（也称作*目标存储桶*）。目标存储桶必须位于源存储桶所在的 AWS 区域和 AWS 账户中。

访问日志记录包含有关对存储桶做出的请求的详细信息。这些信息可能包括请求类型、请求中指定的资源以及处理请求的时间和日期。有关日志记录基本知识的更多信息，请参阅 [使用服务器访问日志记录来记录请求](ServerLogs.md)。

**重要**  
在 Amazon S3 存储桶上启用服务器访问日志记录不收取额外费用。但是，系统提交给您的任何日志文件都会产生普通存储费用。(您可以随时删除日志文件。) 我们不会估计传输日志文件的数据传输费，但会按正常数据传输费率对访问日志文件收费。
您的目标存储桶不应启用服务器访问日志记录。您可以让日志传输至您拥有的且与源存储桶位于同一区域中的任何存储桶，包括源存储桶本身。但是，将日志传输到源存储桶会导致日志的无限循环，因此不建议这样做。为了更方便地管理日志，我们建议您将访问日志保存在不同的存储桶中。有关更多信息，请参阅 [如何启用日志传送？](ServerLogs.md#server-access-logging-overview)。
已启用 S3 对象锁定的 S3 存储桶不能用作服务器访问日志的目标存储桶。目标存储桶不得具有默认保留期配置。
目标存储桶不得启用“申请方付款”。

您可以使用 Amazon S3 控制台、Amazon S3 API、AWS Command Line Interface（AWS CLI）或 AWS SDK 启用或禁用服务器访问日志记录。

## 日志传输的权限
<a name="grant-log-delivery-permissions-general"></a>

Amazon S3 使用特殊的日志传输账户写入服务器访问日志。这些写入受常规的访问控制限制。对于访问日志传输，您必须向日志记录服务主体（`logging.s3.amazonaws.com`）授予对目标存储桶的访问权限。

要向 Amazon S3 授予日志传输权限，您可以使用存储桶策略或存储桶访问控制列表（ACL），具体取决于目标存储桶的 S3 对象所有权设置。但是，建议您使用存储桶策略，而不是 ACL。

**S3 对象所有权的强制存储桶拥有者设置**  
如果目标存储桶使用对象所有权的强制存储桶拥有者设置，ACL 将被禁用，并且不再影响权限。在这种情况下，您必须更新目标存储桶的存储桶策略，以向日志记录服务主体授予访问权限。您无法更新存储桶 ACL 以授予对 S3 日志传输组的访问权限。您也无法在 [https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLogging.html](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLogging.html) 配置中包含目的地授权（也称为*目标授权*）。

有关将现有存储桶 ACL 以便将访问日志传输迁移到存储桶策略的信息，请参阅 [为服务器访问日志记录授予对 S3 日志传输组的访问权限](object-ownership-migrating-acls-prerequisites.md#object-ownership-server-access-logs)。有关对象所有权的更多信息，请参阅[为您的存储桶控制对象所有权和禁用 ACL。](about-object-ownership.md)。当您创建新存储桶时，默认情况下 ACL 处于禁用状态。

**使用存储桶策略授予访问权限**  
要使用目标存储桶的存储桶策略授予访问权限，请更新存储桶策略以向日志记录服务主体授予 `s3:PutObject` 权限。如果您使用 Amazon S3 控制台启用服务器访问日志记录，该控制台会自动更新目标存储桶的存储桶策略，以便将此权限授予日志记录服务主体。如果以编程方式启用服务器访问日志记录，则必须手动更新目标存储桶的存储桶策略以向日志记录服务主体授予访问权限。

有关向日志服务主体授予访问权限的存储桶策略示例，请参阅[使用存储桶策略向日志记录服务主体授予权限](#grant-log-delivery-permissions-bucket-policy)。

**使用存储桶 ACL 授予访问权限**  
您也可以使用存储桶 ACL 授予访问日志传输的访问权限。您可以在存储桶 ACL 中添加一个授予条目，以授予对 S3 日志传输组的 `WRITE` 和 `READ_ACP` 权限。但是，不建议使用存储桶 ACL 授予对 S3 日志传输组的访问权限。有关更多信息，请参阅 [为您的存储桶控制对象所有权和禁用 ACL。](about-object-ownership.md)。有关将现有存储桶 ACL 以便将访问日志传输迁移到存储桶策略的信息，请参阅 [为服务器访问日志记录授予对 S3 日志传输组的访问权限](object-ownership-migrating-acls-prerequisites.md#object-ownership-server-access-logs)。有关向日志记录服务主体授予访问权限的示例 ACL，请参阅[使用存储桶 ACL 向日志传输组授予权限](#grant-log-delivery-permissions-acl)。

### 使用存储桶策略向日志记录服务主体授予权限
<a name="grant-log-delivery-permissions-bucket-policy"></a>

此示例存储桶策略向日志记录服务主体（`logging.s3.amazonaws.com`）授予 `s3:PutObject` 权限。要使用这一存储桶策略，请将 `user input placeholders` 替换为您自己的信息。在以下策略中，`amzn-s3-demo-destination-bucket` 是将服务器访问日志传输到的目标存储桶，`amzn-s3-demo-source-bucket` 是源存储桶。`EXAMPLE-LOGGING-PREFIX` 是要用于日志对象的可选目的地前缀（也称为*目标前缀*）。`SOURCE-ACCOUNT-ID` 是拥有源存储桶的 AWS 账户。

**注意**  
如果存储桶策略中有 `Deny` 语句，请确保这些语句不会阻止 Amazon S3 传输访问日志。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "S3ServerAccessLogsPolicy",
            "Effect": "Allow",
            "Principal": {
                "Service": "logging.s3.amazonaws.com"
            },
            "Action": [
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::amzn-s3-demo-destination-bucket/EXAMPLE-LOGGING-PREFIX*",
            "Condition": {
                "ArnLike": {
                    "aws:SourceArn": "arn:aws:s3:::amzn-s3-demo-source-bucket"
                },
                "StringEquals": {
                    "aws:SourceAccount": "SOURCE-ACCOUNT-ID"
                }
            }
        }
    ]
}
```

------

### 使用存储桶 ACL 向日志传输组授予权限
<a name="grant-log-delivery-permissions-acl"></a>

**注意**  
作为安全最佳实践，默认情况下，Amazon S3 在所有新存储桶中禁用访问控制列表（ACL）。有关使用 Amazon S3 控制台 ACL 权限的更多信息，请参阅 [配置 ACL](managing-acls.md)。

我们建议您不要使用此方法，而是使用存储桶 ACL 向日志传输组授予权限。但是，如果目标存储桶使用对象所有权的强制存储桶拥有者设置，则无法设置存储桶或对象 ACL。您也无法在 [https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLogging.html](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLogging.html) 配置中包含目的地授权（也称为*目标授权*）。而是必须使用存储桶策略向日志记录服务主体（`logging.s3.amazonaws.com`）授予访问权限。有关更多信息，请参阅 [日志传输的权限](#grant-log-delivery-permissions-general)。

在存储桶 ACL 中，日志传输组通过以下 URL 表示：

```
1. http://acs.amazonaws.com/groups/s3/LogDelivery
```

要授予 `WRITE` 和 `READ_ACP`（ACL 读取）权限，请将以下授权添加到目标存储桶 ACL：

```
 1. <Grant>
 2.     <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:type="Group">
 3.         <URI>http://acs.amazonaws.com/groups/s3/LogDelivery</URI> 
 4.     </Grantee>
 5.     <Permission>WRITE</Permission>
 6. </Grant>
 7. <Grant>
 8.     <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:type="Group">
 9.         <URI>http://acs.amazonaws.com/groups/s3/LogDelivery</URI> 
10.     </Grantee>
11.     <Permission>READ_ACP</Permission>
12. </Grant>
```

有关以编程方式添加 ACL 授权的示例，请参阅 [配置 ACL](managing-acls.md)。

**重要**  
当您对存储桶使用 AWS CloudFormation 来启用 Amazon S3 服务器访问日志记录，并使用 ACL 向 S3 日志传输组授予访问权限时，您还必须向 CloudFormation 模板添加 "`AccessControl": "LogDeliveryWrite"`。这样做非常重要，因为您只能通过为存储桶创建 ACL 来授予这些权限，而无法在 CloudFormation 中为存储桶创建自定义 ACL。您只能将标准 ACL 与 CloudFormation 结合使用。

## 要启用服务器访问日志记录
<a name="enable-server-logging"></a>

要使用 Amazon S3 控制台、Amazon S3 REST API、AWS SDK 和 AWS CLI 启用服务器访问日志记录，请使用以下过程。

### 使用 S3 控制台
<a name="server-access-logging"></a>

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

1. 在左侧导航窗格中，选择**通用存储桶**。

1. 在存储桶列表中，选择要为其启用服务器访问日志记录的存储桶的名称。

1. 选择 **Properties (属性)**。

1. 在 **Server access logging (服务器访问日志记录)** 部分中，请选择 **Edit (编辑)**。

1. 在**服务器访问日志记录**下，选择**启用**。

1. 在**目标存储桶**下，指定存储桶和可选前缀。如果您指定前缀，建议您在前缀后面加上正斜杠（`/`），以便更轻松地查找日志。
**注意**  
通过斜杠（`/`）指定前缀可让您更轻松地查找日志对象。例如，如果您指定前缀值 `logs/`，则 Amazon S3 创建的每个日志对象的键均以 `logs/` 前缀开头，如下所示：  

   ```
   logs/2013-11-01-21-32-16-E568B2907131C0C0
   ```
如果指定前缀值 `logs`，则日志对象如下所示：  

   ```
   logs2013-11-01-21-32-16-E568B2907131C0C0
   ```

1. 在**日志对象件格式**下，执行下列操作之一：
   + 要选择非基于日期的分区，请选择 **[DestinationPrefix][YYYY]-[MM]-[DD]-[hh]-[mm]-[ss]-[UniqueString]**。
   + 要选择基于日期的分区，请选择 **[DestinationPrefix][SourceAccountId]/[SourceRegion]/[SourceBucket]/[YYYY]/[MM]/[DD]/[YYYY]-[MM]-[DD]-[hh]-[mm]-[ss]-[UniqueString]**，然后选择 **S3 事件时间**或**日志文件传输时间**。

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

   当您在存储桶上启用服务器访问日志记录时，控制台会在源存储桶上启用日志记录并更新目标存储桶的存储桶策略，以便向日志记录服务主体（`logging.s3.amazonaws.com`）授予 `s3:PutObject` 权限。有关存储桶策略的更多信息，请参阅 [使用存储桶策略向日志记录服务主体授予权限](#grant-log-delivery-permissions-bucket-policy)。

   您可以查看目标存储桶中的日志。启用服务器访问日志记录后，可能需要数小时，日志才会传输到目标存储桶。有关如何以及何时传输日志的更多信息，请参阅[如何传输日志？](ServerLogs.md#how-logs-delivered)。

有关更多信息，请参阅 [查看 S3 通用存储桶的属性](view-bucket-properties.md)。

### 使用 REST API
<a name="enable-logging-rest"></a>

要启用日志记录，请提交 [https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlogging.html](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlogging.html) 请求，以在源存储桶上添加日志记录配置。该请求指定目的地存储桶（也称作*目标存储桶*），并（可选）指定要用于所有日志对象键的前缀。

以下示例将 `amzn-s3-demo-destination-bucket` 标识为目标存储桶，将 *`logs/`* 标识为前缀。

```
1. <BucketLoggingStatus xmlns="http://doc.s3.amazonaws.com/2006-03-01">
2.   <LoggingEnabled>
3.     <TargetBucket>amzn-s3-demo-destination-bucket</TargetBucket>
4.     <TargetPrefix>logs/</TargetPrefix>
5.   </LoggingEnabled>
6. </BucketLoggingStatus>
```

以下示例将 `amzn-s3-demo-destination-bucket` 标识为目标存储桶，将 *`logs/`* 标识为前缀，并将 `EventTime` 标识为日志对象键格式。

```
 1. <BucketLoggingStatus xmlns="http://doc.s3.amazonaws.com/2006-03-01">
 2.   <LoggingEnabled>
 3.     <TargetBucket>amzn-s3-demo-destination-bucket</TargetBucket>
 4.     <TargetPrefix>logs/</TargetPrefix>
 5.     <TargetObjectKeyFormat>
 6.       <PartitionedPrefix>
 7.          <PartitionDateSource>EventTime</PartitionDateSource>
 8.       </PartitionedPrefix>
 9.   </TargetObjectKeyFormat>
10.   </LoggingEnabled>
11. </BucketLoggingStatus>
```

日志对象由 S3 日志传递账户编写并拥有，存储桶拥有者对日志对象授予完全权限。您可以选择性地使用目的地授权（也称作*目标授权*）向其他用户授予权限，以便他们能够访问日志。有关更多信息，请参阅 [https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlogging.html](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlogging.html)。

**注意**  
如果目标存储桶使用对象所有权的强制存储桶拥有者设置，则您无法使用目标授权向其他用户授予权限。要向其他用户授予权限，您可以更新目标存储桶的存储桶策略。有关更多信息，请参阅 [日志传输的权限](#grant-log-delivery-permissions-general)。

要检索存储桶上的日志记录配置，请使用 [https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlogging.html](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlogging.html) API 操作。

要删除日志记录配置，请发送带空白 `BucketLoggingStatus` 的 `PutBucketLogging` 请求：

```
1. <BucketLoggingStatus xmlns="http://doc.s3.amazonaws.com/2006-03-01">
2. </BucketLoggingStatus>
```

要对存储桶启用日志记录，您可以使用 Amazon S3 API 或 AWS SDK 包装程序库。

### 使用 AWS SDK
<a name="enable-logging-sdk"></a>

以下示例对存储桶启用日志记录。您必须创建两个存储桶，即一个源存储桶和一个目的地（目标）存储桶。这些示例首先更新目标存储桶上的存储桶 ACL。之后，向日志传输组授予向目标存储桶写入日志所需的权限，然后在源存储桶上启用日志记录。

这些示例不适用于使用对象所有权的强制存储桶拥有者设置的目标存储桶。

如果目的地（目标）存储桶使用对象所有权的强制存储桶拥有者设置，则无法设置存储桶或对象 ACL。您也不能将目的地（目标）授权包含在 [PutBucketLogging](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLogging.html) 配置中。您必须使用存储桶策略向日志服务主体（`logging.s3.amazonaws.com`）授予访问权限。有关更多信息，请参阅 [日志传输的权限](#grant-log-delivery-permissions-general)。

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 查看 GitHub，了解更多信息。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;
    using Microsoft.Extensions.Configuration;

    /// <summary>
    /// This example shows how to enable logging on an Amazon Simple Storage
    /// Service (Amazon S3) bucket. You need to have two Amazon S3 buckets for
    /// this example. The first is the bucket for which you wish to enable
    /// logging, and the second is the location where you want to store the
    /// logs.
    /// </summary>
    public class ServerAccessLogging
    {
        private static IConfiguration _configuration = null!;

        public static async Task Main()
        {
            LoadConfig();

            string bucketName = _configuration["BucketName"];
            string logBucketName = _configuration["LogBucketName"];
            string logObjectKeyPrefix = _configuration["LogObjectKeyPrefix"];
            string accountId = _configuration["AccountId"];

            // If the AWS Region defined for your default user is different
            // from the Region where your Amazon S3 bucket is located,
            // pass the Region name to the Amazon S3 client object's constructor.
            // For example: RegionEndpoint.USWest2 or RegionEndpoint.USEast2.
            IAmazonS3 client = new AmazonS3Client();

            try
            {
                // Update bucket policy for target bucket to allow delivery of logs to it.
                await SetBucketPolicyToAllowLogDelivery(
                    client,
                    bucketName,
                    logBucketName,
                    logObjectKeyPrefix,
                    accountId);

                // Enable logging on the source bucket.
                await EnableLoggingAsync(
                    client,
                    bucketName,
                    logBucketName,
                    logObjectKeyPrefix);
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine($"Error: {e.Message}");
            }
        }

        /// <summary>
        /// This method grants appropriate permissions for logging to the
        /// Amazon S3 bucket where the logs will be stored.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client which will be used
        /// to apply the bucket policy.</param>
        /// <param name="sourceBucketName">The name of the source bucket.</param>
        /// <param name="logBucketName">The name of the bucket where logging
        /// information will be stored.</param>
        /// <param name="logPrefix">The logging prefix where the logs should be delivered.</param>
        /// <param name="accountId">The account id of the account where the source bucket exists.</param>
        /// <returns>Async task.</returns>
        public static async Task SetBucketPolicyToAllowLogDelivery(
            IAmazonS3 client,
            string sourceBucketName,
            string logBucketName,
            string logPrefix,
            string accountId)
        {
            var resourceArn = @"""arn:aws:s3:::" + logBucketName + "/" + logPrefix + @"*""";

            var newPolicy = @"{
                                ""Statement"":[{
                                ""Sid"": ""S3ServerAccessLogsPolicy"",
                                ""Effect"": ""Allow"",
                                ""Principal"": { ""Service"": ""logging.s3.amazonaws.com"" },
                                ""Action"": [""s3:PutObject""],
                                ""Resource"": [" + resourceArn + @"],
                                ""Condition"": {
                                ""ArnLike"": { ""aws:SourceArn"": ""arn:aws:s3:::" + sourceBucketName + @""" },
                                ""StringEquals"": { ""aws:SourceAccount"": """ + accountId + @""" }
                                        }
                                    }]
                                }";
            Console.WriteLine($"The policy to apply to bucket {logBucketName} to enable logging:");
            Console.WriteLine(newPolicy);

            PutBucketPolicyRequest putRequest = new PutBucketPolicyRequest
            {
                BucketName = logBucketName,
                Policy = newPolicy,
            };
            await client.PutBucketPolicyAsync(putRequest);
            Console.WriteLine("Policy applied.");
        }

        /// <summary>
        /// This method enables logging for an Amazon S3 bucket. Logs will be stored
        /// in the bucket you selected for logging. Selected prefix
        /// will be prepended to each log object.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client which will be used
        /// to configure and apply logging to the selected Amazon S3 bucket.</param>
        /// <param name="bucketName">The name of the Amazon S3 bucket for which you
        /// wish to enable logging.</param>
        /// <param name="logBucketName">The name of the Amazon S3 bucket where logging
        /// information will be stored.</param>
        /// <param name="logObjectKeyPrefix">The prefix to prepend to each
        /// object key.</param>
        /// <returns>Async task.</returns>
        public static async Task EnableLoggingAsync(
            IAmazonS3 client,
            string bucketName,
            string logBucketName,
            string logObjectKeyPrefix)
        {
            Console.WriteLine($"Enabling logging for bucket {bucketName}.");
            var loggingConfig = new S3BucketLoggingConfig
            {
                TargetBucketName = logBucketName,
                TargetPrefix = logObjectKeyPrefix,
            };

            var putBucketLoggingRequest = new PutBucketLoggingRequest
            {
                BucketName = bucketName,
                LoggingConfig = loggingConfig,
            };
            await client.PutBucketLoggingAsync(putBucketLoggingRequest);
            Console.WriteLine($"Logging enabled.");
        }

        /// <summary>
        /// Loads configuration from settings files.
        /// </summary>
        public static void LoadConfig()
        {
            _configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("settings.json") // Load settings from .json file.
                .AddJsonFile("settings.local.json", true) // Optionally, load local settings.
                .Build();
        }
    }
```
+  有关更多信息，请参阅《适用于 .NET 的 AWS SDK API 参考》**中的 [PutBucketLogging](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutBucketLogging)。

------
#### [ Java ]

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.BucketLoggingStatus;
import software.amazon.awssdk.services.s3.model.LoggingEnabled;
import software.amazon.awssdk.services.s3.model.PartitionedPrefix;
import software.amazon.awssdk.services.s3.model.PutBucketLoggingRequest;
import software.amazon.awssdk.services.s3.model.TargetObjectKeyFormat;

// Class to set a bucket policy on a target S3 bucket and enable server access logging on a source S3 bucket.
public class ServerAccessLogging {
    private static S3Client s3Client;

    public static void main(String[] args) {
        String sourceBucketName = "SOURCE-BUCKET";
        String targetBucketName = "TARGET-BUCKET";
        String sourceAccountId = "123456789012";
        String targetPrefix = "logs/";

        // Create S3 Client.
        s3Client = S3Client.builder().
                region(Region.US_EAST_2)
                .build();

        // Set a bucket policy on the target S3 bucket to enable server access logging by granting the
        // logging.s3.amazonaws.com principal permission to use the PutObject operation.
        ServerAccessLogging serverAccessLogging = new ServerAccessLogging();
        serverAccessLogging.setTargetBucketPolicy(sourceAccountId, sourceBucketName, targetBucketName);

        // Enable server access logging on the source S3 bucket.
        serverAccessLogging.enableServerAccessLogging(sourceBucketName, targetBucketName,
                targetPrefix);

    }

    // Function to set a bucket policy on the target S3 bucket to enable server access logging by granting the
    // logging.s3.amazonaws.com principal permission to use the PutObject operation.
    public void setTargetBucketPolicy(String sourceAccountId, String sourceBucketName, String targetBucketName) {
        String policy = "{\n" +
                "    \"Version\": \"2012-10-17\",\n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Sid\": \"S3ServerAccessLogsPolicy\",\n" +
                "            \"Effect\": \"Allow\",\n" +
                "            \"Principal\": {\"Service\": \"logging.s3.amazonaws.com\"},\n" +
                "            \"Action\": [\n" +
                "                \"s3:PutObject\"\n" +
                "            ],\n" +
                "            \"Resource\": \"arn:aws:s3:::" + targetBucketName + "/*\",\n" +
                "            \"Condition\": {\n" +
                "                \"ArnLike\": {\n" +
                "                    \"aws:SourceArn\": \"arn:aws:s3:::" + sourceBucketName + "\"\n" +
                "                },\n" +
                "                \"StringEquals\": {\n" +
                "                    \"aws:SourceAccount\": \"" + sourceAccountId + "\"\n" +
                "                }\n" +
                "            }\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        s3Client.putBucketPolicy(b -> b.bucket(targetBucketName).policy(policy));
    }

    // Function to enable server access logging on the source S3 bucket.
    public void enableServerAccessLogging(String sourceBucketName, String targetBucketName,
            String targetPrefix) {
        TargetObjectKeyFormat targetObjectKeyFormat = TargetObjectKeyFormat.builder()
                .partitionedPrefix(PartitionedPrefix.builder().partitionDateSource("EventTime").build())
                .build();
        LoggingEnabled loggingEnabled = LoggingEnabled.builder()
                .targetBucket(targetBucketName)
                .targetPrefix(targetPrefix)
                .targetObjectKeyFormat(targetObjectKeyFormat)
                .build();
        BucketLoggingStatus bucketLoggingStatus = BucketLoggingStatus.builder()
                .loggingEnabled(loggingEnabled)
                .build();
        s3Client.putBucketLogging(PutBucketLoggingRequest.builder()
                .bucket(sourceBucketName)
                .bucketLoggingStatus(bucketLoggingStatus)
                .build());
    }

}
```

------

### 使用 AWS CLI
<a name="enabling-s3-access-logs-for-requests"></a>

我们建议您在其中放置 S3 存储桶的每个 AWS 区域 中都创建一个专用日志记录存储桶。然后，将 Amazon S3 访问日志传输到该 S3 存储桶。有关更多信息和示例，请参阅《AWS CLI 参考》**中的 [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-logging.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-logging.html)。

如果目的地（目标）存储桶使用对象所有权的强制存储桶拥有者设置，则无法设置存储桶或对象 ACL。您也不能将目的地（目标）授权包含在 [PutBucketLogging](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLogging.html) 配置中。您必须使用存储桶策略向日志服务主体（`logging.s3.amazonaws.com`）授予访问权限。有关更多信息，请参阅 [日志传输的权限](#grant-log-delivery-permissions-general)。

**Example — 为跨两个区域的五个存储桶启用访问日志**  
在本示例中，您有以下 5 个存储桶：  
+ `amzn-s3-demo-source-bucket-us-east-1`
+ `amzn-s3-demo-source-bucket1-us-east-1`
+ `amzn-s3-demo-source-bucket2-us-east-1`
+ `amzn-s3-demo-bucket1-us-west-2`
+ `amzn-s3-demo-bucket2-us-west-2`
**注意**  
以下过程的最后一步提供了示例 bash 脚本，可使用这些脚本来创建日志记录存储桶，并在这些存储桶上启用服务器访问日志记录。要使用这些脚本，必须创建 `policy.json` 和 `logging.json` 文件，如以下过程所述。

1. 在美国西部（俄勒冈州）和美国东部（弗吉尼亚州北部）区域创建两个日志记录存储桶，并为其指定以下名称：
   + `amzn-s3-demo-destination-bucket-logs-us-east-1`
   + `amzn-s3-demo-destination-bucket1-logs-us-west-2`

1. 稍后，在这些步骤中，您将启用服务器访问日志记录，如下所示：
   + `amzn-s3-demo-source-bucket-us-east-1` 记录到带有前缀 `amzn-s3-demo-source-bucket-us-east-1` 的 S3 存储桶 `amzn-s3-demo-destination-bucket-logs-us-east-1`
   + `amzn-s3-demo-source-bucket1-us-east-1` 记录到带有前缀 `amzn-s3-demo-source-bucket1-us-east-1` 的 S3 存储桶 `amzn-s3-demo-destination-bucket-logs-us-east-1`
   + `amzn-s3-demo-source-bucket2-us-east-1` 记录到带有前缀 `amzn-s3-demo-source-bucket2-us-east-1` 的 S3 存储桶 `amzn-s3-demo-destination-bucket-logs-us-east-1`
   + `amzn-s3-demo-bucket1-us-west-2` 记录到带有前缀 `amzn-s3-demo-bucket1-us-west-2` 的 S3 存储桶 `amzn-s3-demo-destination-bucket1-logs-us-west-2`
   + `amzn-s3-demo-bucket2-us-west-2` 记录到带有前缀 `amzn-s3-demo-bucket2-us-west-2` 的 S3 存储桶 `amzn-s3-demo-destination-bucket1-logs-us-west-2`

1. 对于每个目标日志记录存储桶，使用存储桶 ACL *或*存储桶策略授予服务器访问日志传输的权限：
   + **更新存储桶策略**（建议）– 要向日志记录服务主体授予权限，请使用以下 `put-bucket-policy` 命令：将 `amzn-s3-demo-destination-bucket-logs` 替换为您的目标桶的名称。

     ```
     1. aws s3api put-bucket-policy --bucket amzn-s3-demo-destination-bucket-logs --policy file://policy.json
     ```

     `Policy.json` 是当前文件夹中包含以下存储桶策略的 JSON 文档。要使用这一存储桶策略，请将 `user input placeholders` 替换为您自己的信息。在以下策略中，*`amzn-s3-demo-destination-bucket-logs`* 是要将服务器访问日志传输到的目标存储桶，`amzn-s3-demo-source-bucket` 是源存储桶。`SOURCE-ACCOUNT-ID` 是拥有源存储桶的 AWS 账户。

------
#### [ JSON ]

****  

     ```
     {
         "Version":"2012-10-17",		 	 	 
         "Statement": [
             {
                 "Sid": "S3ServerAccessLogsPolicy",
                 "Effect": "Allow",
                 "Principal": {
                     "Service": "logging.s3.amazonaws.com"
                 },
                 "Action": [
                     "s3:PutObject"
                 ],
                 "Resource": "arn:aws:s3:::amzn-s3-demo-destination-bucket-logs/*",
                 "Condition": {
                     "ArnLike": {
                         "aws:SourceArn": "arn:aws:s3:::amzn-s3-demo-source-bucket"
                     },
                     "StringEquals": {
                         "aws:SourceAccount": "SOURCE-ACCOUNT-ID"
                     }
                 }
             }
         ]
     }
     ```

------
   + **更新存储桶 ACL** –要向 S3 日志传输组授予权限，请使用以下 `put-bucket-acl` 命令。将 *`amzn-s3-demo-destination-bucket-logs`* 替换为您的目的地（目标）存储桶的名称。

     ```
     1. aws s3api put-bucket-acl --bucket amzn-s3-demo-destination-bucket-logs  --grant-write URI=http://acs.amazonaws.com/groups/s3/LogDelivery --grant-read-acp URI=http://acs.amazonaws.com/groups/s3/LogDelivery 
     ```

1. 然后，创建一个包含日志记录配置的 `logging.json` 文件（基于以下三个示例之一）。创建 `logging.json` 文件后，可以使用以下 `put-bucket-logging` 命令应用日志记录配置。将 *`amzn-s3-demo-destination-bucket-logs`* 替换为您的目的地（目标）存储桶的名称。

   ```
   1. aws s3api put-bucket-logging --bucket amzn-s3-demo-destination-bucket-logs --bucket-logging-status file://logging.json 
   ```
**注意**  
您可以使用下一步中提供的 bash 脚本之一，而不是使用此 `put-bucket-logging` 命令在每个目标存储桶上应用日志记录配置。要使用这些脚本，您必须创建 `policy.json` 和 `logging.json` 文件，如该过程所述。

   `logging.json` 文件是当前文件夹中包含日志记录配置的 JSON 文档。如果目标存储桶使用对象所有权的强制存储桶拥有者设置，则您的日志记录配置不能包含目的地（目标）授权。有关更多信息，请参阅 [日志传输的权限](#grant-log-delivery-permissions-general)。  
**Example – `logging.json`，不带目的地（目标）授权**  

   以下示例 `logging.json` 文件不包含目的地（目标）授权。因此，您可以将此配置应用于使用对象所有权的强制存储桶拥有者设置的目的地（目标）存储桶。

   ```
     {
         "LoggingEnabled": {
             "TargetBucket": "amzn-s3-demo-destination-bucket-logs",
             "TargetPrefix": "amzn-s3-demo-destination-bucket/"
          }
      }
   ```  
**Example – `logging.json`，带目的地（目标）授权**  

   以下示例 `logging.json` 文件包含目的地（目标）授权。

   如果目标存储桶使用对象所有权的强制存储桶拥有者设置，则您无法在 [https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLogging.html](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLogging.html) 配置中包含目的地（目标）授权。有关更多信息，请参阅 [日志传输的权限](#grant-log-delivery-permissions-general)。

   ```
     {
         "LoggingEnabled": {
             "TargetBucket": "amzn-s3-demo-destination-bucket-logs",
             "TargetPrefix": "amzn-s3-demo-destination-bucket/",
             "TargetGrants": [
                  {
                     "Grantee": {
                         "Type": "CanonicalUser",
                         "ID": "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be"
                      },
                     "Permission": "FULL_CONTROL"
                  }
              ]
          }
      }
   ```

**被授权者值**  
您可以通过以下方式（使用请求元素）指定要向其分配访问权限的人员（被授权者）：
   + 按人员的 ID：

     ```
     {
       "Grantee": {
         "Type": "CanonicalUser",
         "ID": "ID"
       }
     }
     ```
   + 按 URI：

     ```
     {
       "Grantee": {
         "Type": "Group",
         "URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"
       }
     }
     ```  
**Example – `logging.json`，日志对象键格式设置为 S3 事件时间**  

   以下 `logging.json` 文件将日志对象键格式更改为 S3 事件时间。有关设置日志对象键格式的更多信息，请参阅[如何启用日志传送？](ServerLogs.md#server-access-logging-overview)

   ```
     { 
       "LoggingEnabled": {
           "TargetBucket": "amzn-s3-demo-destination-bucket-logs",
           "TargetPrefix": "amzn-s3-demo-destination-bucket/",
           "TargetObjectKeyFormat": { 
               "PartitionedPrefix": { 
                   "PartitionDateSource": "EventTime" 
               }
            }
       }
   }
   ```

1. 使用下列 bash 脚本之一为您账户中的所有存储桶添加访问日志记录。将 *`amzn-s3-demo-destination-bucket-logs`* 替换为目的地（目标）存储桶的名称，并将 `us-west-2` 替换为存储桶所在的区域的名称。
**注意**  
此脚本仅在所有存储桶均位于同一区域中时有用。如果您在多个区域中有存储桶，则必须调整该脚本。  
**Example — 使用存储桶策略授予访问权限并为账户中的存储桶添加日志记录**  

   ```
     loggingBucket='amzn-s3-demo-destination-bucket-logs'
     region='us-west-2'
     
     
     # Create the logging bucket.
     aws s3 mb s3://$loggingBucket --region $region
     
     aws s3api put-bucket-policy --bucket $loggingBucket --policy file://policy.json
     
     # List the buckets in this account.
     buckets="$(aws s3 ls | awk '{print $3}')"
     
     # Put a bucket logging configuration on each bucket.
     for bucket in $buckets
         do 
           # This if statement excludes the logging bucket.
           if [ "$bucket" == "$loggingBucket" ] ; then
               continue;
           fi
           printf '{
             "LoggingEnabled": {
               "TargetBucket": "%s",
               "TargetPrefix": "%s/"
           }
         }' "$loggingBucket" "$bucket"  > logging.json
         aws s3api put-bucket-logging --bucket $bucket --bucket-logging-status file://logging.json
         echo "$bucket done"
     done
     
     rm logging.json
     
     echo "Complete"
   ```  
**Example — 使用存储桶 ACL 授予访问权限并为账户中的存储桶添加日志记录**  

   ```
     loggingBucket='amzn-s3-demo-destination-bucket-logs'
     region='us-west-2'
     
     
     # Create the logging bucket.
     aws s3 mb s3://$loggingBucket --region $region
     
     aws s3api put-bucket-acl --bucket $loggingBucket --grant-write URI=http://acs.amazonaws.com/groups/s3/LogDelivery --grant-read-acp URI=http://acs.amazonaws.com/groups/s3/LogDelivery
     
     # List the buckets in this account.
     buckets="$(aws s3 ls | awk '{print $3}')"
     
     # Put a bucket logging configuration on each bucket.
     for bucket in $buckets
         do 
           # This if statement excludes the logging bucket.
           if [ "$bucket" == "$loggingBucket" ] ; then
               continue;
           fi
           printf '{
             "LoggingEnabled": {
               "TargetBucket": "%s",
               "TargetPrefix": "%s/"
           }
         }' "$loggingBucket" "$bucket"  > logging.json
         aws s3api put-bucket-logging --bucket $bucket --bucket-logging-status file://logging.json
         echo "$bucket done"
     done
     
     rm logging.json
     
     echo "Complete"
   ```

## 验证服务器访问日志设置
<a name="verify-access-logs"></a>

启用服务器访问日志记录后，请完成以下步骤：
+ 访问目标存储桶并验证是否正在传输日志文件。设置访问日志后，Amazon S3 会立即开始捕获请求并记录这些请求。但是，日志会在数小时后传输到目标存储桶。有关更多信息，请参阅[存储桶日志记录状态更改将逐渐生效](ServerLogs.md#BucketLoggingStatusChanges)和[最大努力服务器日志传输](ServerLogs.md#LogDeliveryBestEffort)。

  还可以通过使用 Amazon S3 请求指标并为这些指标设置 Amazon CloudWatch 警报，来自动验证日志传输。有关更多信息，请参阅 [使用 Amazon CloudWatch 监控指标](cloudwatch-monitoring.md)。
+ 验证您是否能够打开和读取日志文件的内容。

有关服务器访问日志记录故障排除信息，请参阅[排查服务器访问日志记录问题](troubleshooting-server-access-logging.md)。