

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

# 啟用 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 SDKs 來啟用或停用伺服器存取記錄。

## 日誌交付許可
<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 來授予存取日誌交付的存取權。您可以為將 `WRITE` 和 `READ_ACP` 許可授予 S3 日誌交付群組的儲存貯體 ACL 新增授予項目。不過，不建議使用儲存貯體 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>

此範例儲存貯體政策會將 `s3:PutObject` 許可授予記錄服務主體 (`logging.s3.amazonaws.com`)。若要使用此儲存貯體政策，請以您自己的資訊取代 `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 伺服器存取記錄，且您使用 ACLs 授予對 S3 日誌交付群組的存取權時，您還必須將 "`AccessControl": "LogDeliveryWrite"` 新增至 CloudFormation 範本。請務必這樣做，因為您只能透過為儲存貯體建立 ACL 來授予這些許可，而無法在 CloudFormation 中為儲存貯體建立自訂 ACL。您只能搭配 CloudFormation 使用固定 ACL。

## 啟用伺服器存取日誌記錄
<a name="enable-server-logging"></a>

若要使用 Amazon S3 主控台、Amazon S3 REST API、 AWS SDKs 和 啟用伺服器存取記錄 AWS CLI，請使用下列程序。

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

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/) 開啟 Amazon 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. 選擇**儲存變更**。

   在儲存貯體上啟用伺服器存取記錄時，主控台會啟用來源儲存貯體上的記錄，同時更新目的地儲存貯體的儲存貯體政策，以將 `s3:PutObject` 許可授予記錄服務主體 (`logging.s3.amazonaws.com`)。如需此儲存貯體政策的詳細資訊，請參閱 [使用儲存貯體政策授予記錄服務主體的許可](#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 SDKs
<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();
        }
    }
```
+  如需 API 詳細資訊，請參閱《適用於 .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 — 對跨兩個區域的五個儲存貯體啟用存取日誌**  
在此範例中，您擁有下列五個儲存貯體：  
+ `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` 記錄到 S3 儲存貯體 `amzn-s3-demo-destination-bucket-logs-us-east-1`，帶有字首 `amzn-s3-demo-source-bucket-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-bucket1-us-east-1`
   + `amzn-s3-demo-source-bucket2-us-east-1` 記錄到 S3 儲存貯體 `amzn-s3-demo-destination-bucket-logs-us-east-1`，帶有字首 `amzn-s3-demo-source-bucket2-us-east-1`
   + `amzn-s3-demo-bucket1-us-west-2` 記錄到 S3 儲存貯體 `amzn-s3-demo-destination-bucket1-logs-us-west-2`，帶有字首 `amzn-s3-demo-bucket1-us-west-2`
   + `amzn-s3-demo-bucket2-us-west-2` 記錄到 S3 儲存貯體 `amzn-s3-demo-destination-bucket1-logs-us-west-2`，帶有字首 `amzn-s3-demo-bucket2-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)。