

文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 [AWS SDK 範例](https://github.com/awsdocs/aws-doc-sdk-examples)。

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

# CloudTrail AWS SDKs的程式碼範例
<a name="cloudtrail_code_examples"></a>

下列程式碼範例示範如何使用 AWS CloudTrail 搭配 AWS 軟體開發套件 (SDK)。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

**其他資源**
+  **[ CloudTrail 開發人員指南](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html)** – CloudTrail 的相關詳細資訊。
+ **[CloudTrail API 參考](https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/Welcome.html)** – 所有可用 CloudTrail 動作的詳細資訊。
+ **[AWS 開發人員中心](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-product=product%23)** – 您可以依類別或全文搜尋篩選的程式碼範例。
+ **[AWS SDK 範例](https://github.com/awsdocs/aws-doc-sdk-examples)** – GitHub 儲存庫使用慣用語言的完整程式碼。包含設定和執行程式碼的指示。

**Contents**
+ [基本概念](cloudtrail_code_examples_basics.md)
  + [動作](cloudtrail_code_examples_actions.md)
    + [`CreateTrail`](cloudtrail_example_cloudtrail_CreateTrail_section.md)
    + [`DeleteTrail`](cloudtrail_example_cloudtrail_DeleteTrail_section.md)
    + [`DescribeTrail`](cloudtrail_example_cloudtrail_DescribeTrail_section.md)
    + [`DescribeTrails`](cloudtrail_example_cloudtrail_DescribeTrails_section.md)
    + [`GetTrailStatus`](cloudtrail_example_cloudtrail_GetTrailStatus_section.md)
    + [`ListTrails`](cloudtrail_example_cloudtrail_ListTrails_section.md)
    + [`LookupEvents`](cloudtrail_example_cloudtrail_LookupEvents_section.md)
    + [`StartLogging`](cloudtrail_example_cloudtrail_StartLogging_section.md)
    + [`StopLogging`](cloudtrail_example_cloudtrail_StopLogging_section.md)
    + [`UpdateTrail`](cloudtrail_example_cloudtrail_UpdateTrail_section.md)

# 使用 AWS SDKs CloudTrail 基本範例
<a name="cloudtrail_code_examples_basics"></a>

下列程式碼範例示範如何 AWS CloudTrail 搭配 AWS SDKs 使用 的基本概念。

**Contents**
+ [動作](cloudtrail_code_examples_actions.md)
  + [`CreateTrail`](cloudtrail_example_cloudtrail_CreateTrail_section.md)
  + [`DeleteTrail`](cloudtrail_example_cloudtrail_DeleteTrail_section.md)
  + [`DescribeTrail`](cloudtrail_example_cloudtrail_DescribeTrail_section.md)
  + [`DescribeTrails`](cloudtrail_example_cloudtrail_DescribeTrails_section.md)
  + [`GetTrailStatus`](cloudtrail_example_cloudtrail_GetTrailStatus_section.md)
  + [`ListTrails`](cloudtrail_example_cloudtrail_ListTrails_section.md)
  + [`LookupEvents`](cloudtrail_example_cloudtrail_LookupEvents_section.md)
  + [`StartLogging`](cloudtrail_example_cloudtrail_StartLogging_section.md)
  + [`StopLogging`](cloudtrail_example_cloudtrail_StopLogging_section.md)
  + [`UpdateTrail`](cloudtrail_example_cloudtrail_UpdateTrail_section.md)

# CloudTrail 使用 AWS SDKs的動作
<a name="cloudtrail_code_examples_actions"></a>

下列程式碼範例示範如何使用 AWS SDKs 執行個別 CloudTrail 動作。每個範例均包含 GitHub 的連結，您可以在連結中找到設定和執行程式碼的相關說明。

 下列範例僅包含最常使用的動作。如需完整清單，請參閱《[AWS CloudTrail API 參考](https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/Welcome.html)》。

**Topics**
+ [`CreateTrail`](cloudtrail_example_cloudtrail_CreateTrail_section.md)
+ [`DeleteTrail`](cloudtrail_example_cloudtrail_DeleteTrail_section.md)
+ [`DescribeTrail`](cloudtrail_example_cloudtrail_DescribeTrail_section.md)
+ [`DescribeTrails`](cloudtrail_example_cloudtrail_DescribeTrails_section.md)
+ [`GetTrailStatus`](cloudtrail_example_cloudtrail_GetTrailStatus_section.md)
+ [`ListTrails`](cloudtrail_example_cloudtrail_ListTrails_section.md)
+ [`LookupEvents`](cloudtrail_example_cloudtrail_LookupEvents_section.md)
+ [`StartLogging`](cloudtrail_example_cloudtrail_StartLogging_section.md)
+ [`StopLogging`](cloudtrail_example_cloudtrail_StopLogging_section.md)
+ [`UpdateTrail`](cloudtrail_example_cloudtrail_UpdateTrail_section.md)

# `CreateTrail` 搭配 AWS SDK 或 CLI 使用
<a name="cloudtrail_example_cloudtrail_CreateTrail_section"></a>

下列程式碼範例示範如何使用 `CreateTrail`。

------
#### [ C\$1\$1 ]

**適用於 C\$1\$1 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudtrail#code-examples)中設定和執行。

```
// Routine which creates an AWS CloudTrail trail.
/*!
  \param trailName: The name of the CloudTrail trail.
  \param bucketName: The Amazon S3 bucket designate for publishing logs.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::CloudTrail::createTrail(const Aws::String trailName,
                                     const Aws::String bucketName,
                                     const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::CloudTrail::CloudTrailClient trailClient(clientConfig);
    Aws::CloudTrail::Model::CreateTrailRequest request;
    request.SetName(trailName);
    request.SetS3BucketName(bucketName);

    Aws::CloudTrail::Model::CreateTrailOutcome outcome = trailClient.CreateTrail(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully created trail " << trailName << std::endl;
    }
    else {
        std::cerr << "Failed to create trail " << trailName <<
                  ": " << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  如需 API 詳細資訊，請參閱《適用於 C\$1\$1 的 AWS SDK API 參考》**中的 [CreateTrail](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/CreateTrail)。

------
#### [ CLI ]

**AWS CLI**  
**建立追蹤記錄**  
下列 `create-trail` 範例建立名為 `Trail1` 的多區域追蹤記錄，並指定 S3 儲存貯體。  

```
aws cloudtrail create-trail \
    --name Trail1 \
    --s3-bucket-name amzn-s3-demo-bucket \
    --is-multi-region-trail
```
輸出：  

```
{
    "IncludeGlobalServiceEvents": true,
    "Name": "Trail1",
    "TrailARN": "arn:aws:cloudtrail:us-west-2:123456789012:trail/Trail1",
    "LogFileValidationEnabled": false,
    "IsMultiRegionTrail": true,
    "S3BucketName": "amzn-s3-demo-bucket"
}
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [CreateTrail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/create-trail.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：建立使用儲存貯體 'amzn-s3-demo-bucket' 進行日誌檔儲存的追蹤記錄。**  

```
New-CTTrail -Name "awscloudtrail-example" -S3BucketName "amzn-s3-demo-bucket"
```
**範例 2：建立使用儲存貯體 'amzn-s3-demo-bucket' 進行日誌檔儲存的追蹤記錄。代表日誌的 S3 物件具有 'mylogs' 的常用鍵字首。當新日誌交付至儲存貯體時，傳送通知至 SNS 主題 'mlog-deliverytopic'。此範例使用 splatting 將參數值提供給 Cmdlet。**  

```
$params = @{
    Name="awscloudtrail-example"
    S3BucketName="amzn-s3-demo-bucket"
    S3KeyPrefix="mylogs"
    SnsTopicName="mlog-deliverytopic"
}      
New-CTTrail @params
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [CreateTrail](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：建立使用儲存貯體 'amzn-s3-demo-bucket' 進行日誌檔儲存的追蹤記錄。**  

```
New-CTTrail -Name "awscloudtrail-example" -S3BucketName "amzn-s3-demo-bucket"
```
**範例 2：建立使用儲存貯體 'amzn-s3-demo-bucket' 進行日誌檔儲存的追蹤記錄。代表日誌的 S3 物件具有 'mylogs' 的常用鍵字首。當新日誌交付至儲存貯體時，傳送通知至 SNS 主題 'mlog-deliverytopic'。此範例使用 splatting 將參數值提供給 Cmdlet。**  

```
$params = @{
    Name="awscloudtrail-example"
    S3BucketName="amzn-s3-demo-bucket"
    S3KeyPrefix="mylogs"
    SnsTopicName="mlog-deliverytopic"
}      
New-CTTrail @params
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateTrail](https://docs.aws.amazon.com/powershell/v5/reference)。

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudtrail#code-examples)中設定和執行。

```
require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk'
require 'aws-sdk-s3'
require 'aws-sdk-sts'

def create_trail_example(s3_client, sts_client, cloudtrail_client, trail_name, bucket_name)
  resp = sts_client.get_caller_identity({})
  account_id = resp.account

  # Attach policy to an Amazon Simple Storage Service (S3) bucket.
  s3_client.create_bucket(bucket: bucket_name)
  begin
    policy = {
      'Version' => '2012-10-17',
      'Statement' => [
        {
          'Sid' => 'AWSCloudTrailAclCheck20150319',
          'Effect' => 'Allow',
          'Principal' => {
            'Service' => 'cloudtrail.amazonaws.com'
          },
          'Action' => 's3:GetBucketAcl',
          'Resource' => "arn:aws:s3:::#{bucket_name}"
        },
        {
          'Sid' => 'AWSCloudTrailWrite20150319',
          'Effect' => 'Allow',
          'Principal' => {
            'Service' => 'cloudtrail.amazonaws.com'
          },
          'Action' => 's3:PutObject',
          'Resource' => "arn:aws:s3:::#{bucket_name}/AWSLogs/#{account_id}/*",
          'Condition' => {
            'StringEquals' => {
              's3:x-amz-acl' => 'bucket-owner-full-control'
            }
          }
        }
      ]
    }.to_json

    s3_client.put_bucket_policy(
      bucket: bucket_name,
      policy: policy
    )
    puts "Successfully added policy to bucket #{bucket_name}"
  end

  begin
    cloudtrail_client.create_trail({
                                     name: trail_name, # required
                                     s3_bucket_name: bucket_name # required
                                   })

    puts "Successfully created trail: #{trail_name}."
  rescue StandardError => e
    puts "Got error trying to create trail #{trail_name}:\n #{e}"
    puts e
    exit 1
  end
```
+  如需 API 詳細資訊，請參閱《適用於 Ruby 的 AWS SDK API 參考》**中的 [CreateTrail](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/CreateTrail)。

------

# `DeleteTrail` 搭配 AWS SDK 或 CLI 使用
<a name="cloudtrail_example_cloudtrail_DeleteTrail_section"></a>

下列程式碼範例示範如何使用 `DeleteTrail`。

------
#### [ C\$1\$1 ]

**適用於 C\$1\$1 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudtrail#code-examples)中設定和執行。

```
// Routine which deletes an AWS CloudTrail trail.
/*!
  \param trailName: The name of the CloudTrail trail.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::CloudTrail::deleteTrail(const Aws::String trailName,
                                     const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::CloudTrail::CloudTrailClient trailClient(clientConfig);

    Aws::CloudTrail::Model::DeleteTrailRequest request;
    request.SetName(trailName);

    auto outcome = trailClient.DeleteTrail(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted trail " << trailName << std::endl;
    }
    else {
        std::cerr << "Error deleting trail " << trailName << " " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  如需 API 詳細資訊，請參閱《適用於 C\$1\$1 的 AWS SDK API 參考》**中的 [DeleteTrail](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/DeleteTrail)。

------
#### [ CLI ]

**AWS CLI**  
**刪除追蹤記錄**  
以下 `delete-trail` 命令刪除名為 `Trail1` 的追蹤記錄：  

```
aws cloudtrail delete-trail --name Trail1
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DeleteTrail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/delete-trail.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：刪除指定的追蹤記錄。執行命令之前，系統會提示您確認。若要隱藏確認，請新增 -Force 切換變數。**  

```
Remove-CTTrail -Name "awscloudtrail-example"
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V4)*》中的 [DeleteTrail](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：刪除指定的追蹤記錄。執行命令之前，系統會提示您確認。若要隱藏確認，請新增 -Force 切換變數。**  

```
Remove-CTTrail -Name "awscloudtrail-example"
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [DeleteTrail](https://docs.aws.amazon.com/powershell/v5/reference)。

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudtrail#code-examples)中設定和執行。

```
  client.delete_trail({
                        name: trail_name # required
                      })
  puts "Successfully deleted trail: #{trail_name}"
rescue StandardError => e
  puts "Got error trying to delete trail: #{trail_name}:"
  puts e
  exit 1
end
```
+  如需 API 詳細資訊，請參閱《適用於 Ruby 的 AWS SDK API 參考》**中的 [DeleteTrail](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/DeleteTrail)。

------

# `DescribeTrail` 搭配 AWS SDK 使用
<a name="cloudtrail_example_cloudtrail_DescribeTrail_section"></a>

以下程式碼範例顯示如何使用 `DescribeTrail`。

------
#### [ C\$1\$1 ]

**適用於 C\$1\$1 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudtrail#code-examples)中設定和執行。

```
// Routine which describes the AWS CloudTrail trails in an account.
/*!
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/

bool AwsDoc::CloudTrail::describeTrails(
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::CloudTrail::CloudTrailClient cloudTrailClient(clientConfig);
    Aws::CloudTrail::Model::DescribeTrailsRequest request;

    auto outcome = cloudTrailClient.DescribeTrails(request);
    if (outcome.IsSuccess()) {
        const Aws::Vector<Aws::CloudTrail::Model::Trail> &trails = outcome.GetResult().GetTrailList();
        std::cout << trails.size() << " trail(s) found." << std::endl;
        for (const Aws::CloudTrail::Model::Trail &trail: trails) {
            std::cout << trail.GetName() << std::endl;
        }
    }
    else {
        std::cerr << "Failed to describe trails." << outcome.GetError().GetMessage()
                  << std::endl;
    }
    return outcome.IsSuccess();
}
```
+  如需 API 詳細資訊，請參閱《適用於 C\$1\$1 的 AWS SDK API 參考》**中的 [DescribeTrail](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/DescribeTrail)。

------

# 搭配使用 `DescribeTrails` 與 CLI
<a name="cloudtrail_example_cloudtrail_DescribeTrails_section"></a>

下列程式碼範例示範如何使用 `DescribeTrails`。

------
#### [ CLI ]

**AWS CLI**  
**描述追蹤記錄**  
下列 `describe-trails` 範例會傳回 `Trail1` 和 `Trail2` 的設定。  

```
aws cloudtrail describe-trails \
    --trail-name-list Trail1 Trail2
```
輸出：  

```
{
    "trailList": [
        {
            "IncludeGlobalServiceEvents": true,
            "Name": "Trail1",
            "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1",
            "LogFileValidationEnabled": false,
            "IsMultiRegionTrail": false,
            "S3BucketName": "amzn-s3-demo-bucket",
            "CloudWatchLogsRoleArn": "arn:aws:iam::123456789012:role/CloudTrail_CloudWatchLogs_Role",
            "CloudWatchLogsLogGroupArn": "arn:aws:logs:us-east-1:123456789012:log-group:CloudTrail:*",
            "SnsTopicName": "my-topic",
            "HomeRegion": "us-east-1"
        },
        {
            "IncludeGlobalServiceEvents": true,
            "Name": "Trail2",
            "S3KeyPrefix": "my-prefix",
            "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail2",
            "LogFileValidationEnabled": false,
            "IsMultiRegionTrail": false,
            "S3BucketName": "amzn-s3-demo-bucket2",
            "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/4c5ae5ac-3c13-421e-8335-c7868ef6a769",
            "HomeRegion": "us-east-1"
        }
    ]
}
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DescribeTrails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/describe-trails.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：傳回與您的帳戶目前區域相關聯的所有追蹤設定。**  

```
Get-CTTrail
```
**範例 2：傳回指定的追蹤設定。**  

```
Get-CTTrail -TrailNameList trail1,trail2
```
**範例 3：傳回在目前 shell 預設 (在本案例中為法蘭克福 (eu-central-1) 區域) 以外區域中建立的指定追蹤設定。**  

```
Get-CTTrail -TrailNameList trailABC,trailDEF -Region eu-central-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [DescribeTrails](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：傳回與您的帳戶目前區域相關聯的所有追蹤設定。**  

```
Get-CTTrail
```
**範例 2：傳回指定的追蹤設定。**  

```
Get-CTTrail -TrailNameList trail1,trail2
```
**範例 3：傳回在目前 shell 預設 (在本案例中為法蘭克福 (eu-central-1) 區域) 以外區域中建立的指定追蹤設定。**  

```
Get-CTTrail -TrailNameList trailABC,trailDEF -Region eu-central-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeTrails](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `GetTrailStatus` 與 CLI
<a name="cloudtrail_example_cloudtrail_GetTrailStatus_section"></a>

下列程式碼範例示範如何使用 `GetTrailStatus`。

------
#### [ CLI ]

**AWS CLI**  
**取得追蹤的狀態**  
下列 `get-trail-status` 命令傳回 `Trail1` 的交付和記錄詳細資訊：  

```
aws cloudtrail get-trail-status --name Trail1
```
輸出：  

```
{
  "LatestNotificationTime": 1454022144.869,
  "LatestNotificationAttemptSucceeded": "2016-01-28T23:02:24Z",
  "LatestDeliveryAttemptTime": "2016-01-28T23:02:24Z",
  "LatestDeliveryTime": 1454022144.869,
  "TimeLoggingStarted": "2015-11-06T18:36:38Z",
  "LatestDeliveryAttemptSucceeded": "2016-01-28T23:02:24Z",
  "IsLogging": true,
  "LatestCloudWatchLogsDeliveryTime": 1454022144.918,
  "StartLoggingTime": 1446834998.695,
  "StopLoggingTime": 1446834996.933,
  "LatestNotificationAttemptTime": "2016-01-28T23:02:24Z",
  "TimeLoggingStopped": "2015-11-06T18:36:36Z"
}
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [GetTrailStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/get-trail-status.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：傳回名為 'myExampleTrail' 的追蹤狀態資訊。傳回的資料包含交付錯誤、Amazon SNS 和 Amazon S3 錯誤，以及開始和停止追蹤記錄時間的相關資訊。此範例假設追蹤是在與目前 shell 預設值相同的區域中建立的。**  

```
Get-CTTrailStatus -Name myExampleTrail
```
**範例 2：傳回在目前 shell 預設值 (在本案例中為法蘭克福 (eu-central-1) 區域) 以外區域中建立的追蹤狀態資訊。**  

```
Get-CTTrailStatus -Name myExampleTrail -Region eu-central-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [GetTrailStatus](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：傳回名為 'myExampleTrail' 的追蹤狀態資訊。傳回的資料包含交付錯誤、Amazon SNS 和 Amazon S3 錯誤，以及開始和停止追蹤記錄時間的相關資訊。此範例假設追蹤是在與目前 shell 預設值相同的區域中建立的。**  

```
Get-CTTrailStatus -Name myExampleTrail
```
**範例 2：傳回在目前 shell 預設值 (在本案例中為法蘭克福 (eu-central-1) 區域) 以外區域中建立的追蹤狀態資訊。**  

```
Get-CTTrailStatus -Name myExampleTrail -Region eu-central-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetTrailStatus](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# `ListTrails` 搭配 AWS SDK 使用
<a name="cloudtrail_example_cloudtrail_ListTrails_section"></a>

以下程式碼範例顯示如何使用 `ListTrails`。

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudtrail#code-examples)中設定和執行。

```
require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk'

def describe_trails_example(client)
  resp = client.describe_trails({})
  puts "Found #{resp.trail_list.count} trail(s)."

  resp.trail_list.each do |trail|
    puts "Name:           #{trail.name}"
    puts "S3 bucket name: #{trail.s3_bucket_name}"
    puts
  end
```
+  如需 API 詳細資訊，請參閱《適用於 Ruby 的 AWS SDK API 參考》**中的 [ListTrails](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/ListTrails)。

------

# `LookupEvents` 搭配 AWS SDK 或 CLI 使用
<a name="cloudtrail_example_cloudtrail_LookupEvents_section"></a>

下列程式碼範例示範如何使用 `LookupEvents`。

------
#### [ C\$1\$1 ]

**適用於 C\$1\$1 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudtrail#code-examples)中設定和執行。

```
// Routine which looks up events captured by AWS CloudTrail.
/*!
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::CloudTrail::lookupEvents(
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::CloudTrail::CloudTrailClient cloudtrail(clientConfig);

    Aws::String nextToken; // Used for pagination.
    Aws::Vector<Aws::CloudTrail::Model::Event> allEvents;

    Aws::CloudTrail::Model::LookupEventsRequest request;

    size_t count = 0;
    do {
        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }

        Aws::CloudTrail::Model::LookupEventsOutcome outcome = cloudtrail.LookupEvents(
                request);
        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::CloudTrail::Model::Event> &events = outcome.GetResult().GetEvents();
            count += events.size();
            allEvents.insert(allEvents.end(), events.begin(), events.end());
            nextToken = outcome.GetResult().GetNextToken();
        }
        else {
            std::cerr << "Error: " << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    } while (!nextToken.empty() && count <= 50); // Limit to 50 events.

    std::cout << "Found " << allEvents.size() << " event(s)." << std::endl;

    for (auto &event: allEvents) {
        std::cout << "Event name: " << event.GetEventName() << std::endl;
        std::cout << "Event source: " << event.GetEventSource() << std::endl;
        std::cout << "Event id: " << event.GetEventId() << std::endl;
        std::cout << "Resources: " << std::endl;
        for (auto &resource: event.GetResources()) {
            std::cout << "  " << resource.GetResourceName() << std::endl;
        }
    }

    return true;
}
```
+  如需 API 詳細資訊，請參閱《適用於 C\$1\$1 的 AWS SDK API 參考》**中的 [LookupEvents](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/LookupEvents)。

------
#### [ CLI ]

**AWS CLI**  
**查詢追蹤的事件**  
下列 `lookup-events` 命令依屬性 `EventName` 查詢 API 活動事件：  

```
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=ConsoleLogin
```
輸出：  

```
{
  "Events": [
     {
         "EventId": "654ccbc0-ba0d-486a-9076-dbf7274677a7",
         "Username": "my-session-name",
         "EventTime": "2021-11-18T09:41:02-08:00",
         "CloudTrailEvent": "{\"eventVersion\":\"1.02\",\"userIdentity\":{\"type\":\"AssumedRole\",\"principalId\":\"AROAJIKPFTA72SWU4L7T4:my-session-name\",\"arn\":\"arn:aws:sts::123456789012:assumed-role/my-role/my-session-name\",\"accountId\":\"123456789012\",\"sessionContext\":{\"attributes\":{\"mfaAuthenticated\":\"false\",\"creationDate\":\"2016-01-26T21:42:12Z\"},\"sessionIssuer\":{\"type\":\"Role\",\"principalId\":\"AROAJIKPFTA72SWU4L7T4\",\"arn\":\"arn:aws:iam::123456789012:role/my-role\",\"accountId\":\"123456789012\",\"userName\":\"my-role\"}}},\"eventTime\":\"2016-01-26T21:42:12Z\",\"eventSource\":\"signin.amazonaws.com\",\"eventName\":\"ConsoleLogin\",\"awsRegion\":\"us-east-1\",\"sourceIPAddress\":\"72.21.198.70\",\"userAgent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36\",\"requestParameters\":null,\"responseElements\":{\"ConsoleLogin\":\"Success\"},\"additionalEventData\":{\"MobileVersion\":\"No\",\"MFAUsed\":\"No\"},\"eventID\":\"654ccbc0-ba0d-486a-9076-dbf7274677a7\",\"eventType\":\"AwsConsoleSignIn\",\"recipientAccountId\":\"123456789012\"}",
         "EventName": "ConsoleLogin",
         "Resources": []
     }
  ]
}
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [LookupEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/lookup-events.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：傳回過去七天內發生的所有事件。根據預設，Cmdlet 會自動進行多次呼叫以傳遞所有事件，並在服務指出沒有其他資料可用時結束。**  

```
Find-CTEvent
```
**範例 2：傳回過去七天內發生的所有事件，指定不是目前 shell 預設值的區域。**  

```
Find-CTEvent -Region eu-central-1
```
**範例 3：傳回與 RunInstances API 呼叫相關聯的所有事件。**  

```
Find-CTEvent -LookupAttribute @{ AttributeKey="EventName"; AttributeValue="RunInstances" }
```
**範例 4：傳回前 5 個可用的事件。**  

```
Find-CTEvent -MaxResult 5
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [LookupEvents](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：傳回過去七天內發生的所有事件。根據預設，Cmdlet 會自動進行多次呼叫以傳遞所有事件，並在服務指出沒有其他資料可用時結束。**  

```
Find-CTEvent
```
**範例 2：傳回過去七天內發生的所有事件，指定不是目前 shell 預設值的區域。**  

```
Find-CTEvent -Region eu-central-1
```
**範例 3：傳回與 RunInstances API 呼叫相關聯的所有事件。**  

```
Find-CTEvent -LookupAttribute @{ AttributeKey="EventName"; AttributeValue="RunInstances" }
```
**範例 4：傳回前 5 個可用的事件。**  

```
Find-CTEvent -MaxResult 5
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [LookupEvents](https://docs.aws.amazon.com/powershell/v5/reference)。

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudtrail#code-examples)中設定和執行。

```
require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk'

# @param [Object] client
def lookup_events_example(client)
  resp = client.lookup_events
  puts "Found #{resp.events.count} events:"
  resp.events.each do |e|
    puts "Event name:   #{e.event_name}"
    puts "Event ID:     #{e.event_id}"
    puts "Event time:   #{e.event_time}"
    puts 'Resources:'

    e.resources.each do |r|
      puts "  Name:       #{r.resource_name}"
      puts "  Type:       #{r.resource_type}"
      puts ''
    end
  end
end
```
+  如需 API 詳細資訊，請參閱《適用於 Ruby 的 AWS SDK API 參考》**中的 [LookupEvents](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/LookupEvents)。

------

# 搭配使用 `StartLogging` 與 CLI
<a name="cloudtrail_example_cloudtrail_StartLogging_section"></a>

下列程式碼範例示範如何使用 `StartLogging`。

------
#### [ CLI ]

**AWS CLI**  
**啟動追蹤的記錄功能**  
下列 `start-logging` 命令會開啟 `Trail1` 的記錄功能：  

```
aws cloudtrail start-logging --name Trail1
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [StartLogging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/start-logging.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：開始記錄名為 'myExampleTrail' 之線索的 AWS API 呼叫和日誌檔案交付。此範例假設追蹤是在與目前 shell 預設值相同的區域中建立的。**  

```
Start-CTLogging -Name myExampleTrail
```
**範例 2：開始記錄在目前 shell 預設 （在此情況下為法蘭克福 (eu-central-1) 區域） 以外區域中建立之線索的 AWS API 呼叫和日誌檔案交付。**  

```
Start-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [StartLogging](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：開始記錄名為 'myExampleTrail' 之線索的 AWS API 呼叫和日誌檔案交付。此範例假設追蹤是在與目前 shell 預設值相同的區域中建立的。**  

```
Start-CTLogging -Name myExampleTrail
```
**範例 2：開始記錄在目前 shell 預設 （在此情況下為法蘭克福 (eu-central-1) 區域） 以外區域中建立之線索的 AWS API 呼叫和日誌檔案交付。**  

```
Start-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StartLogging](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `StopLogging` 與 CLI
<a name="cloudtrail_example_cloudtrail_StopLogging_section"></a>

下列程式碼範例示範如何使用 `StopLogging`。

------
#### [ CLI ]

**AWS CLI**  
**停止記錄追蹤**  
下列 `stop-logging` 命令會關閉 `Trail1` 的記錄功能：  

```
aws cloudtrail stop-logging --name Trail1
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [StopLogging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/stop-logging.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：暫停記錄名為 'myExampleTrail' 之線索的 AWS API 呼叫和日誌檔案交付。此範例假設追蹤是在與目前 shell 預設值相同的區域中建立的。**  

```
Stop-CTLogging -Name myExampleTrail
```
**範例 2：暫停記錄在目前 shell 預設 （在此情況下為法蘭克福 (eu-central-1) 區域） 以外區域中建立之線索的 AWS API 呼叫和日誌檔案交付。**  

```
Stop-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [StopLogging](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：暫停記錄名為 'myExampleTrail' 之線索的 AWS API 呼叫和日誌檔案交付。此範例假設追蹤是在與目前 shell 預設值相同的區域中建立的。**  

```
Stop-CTLogging -Name myExampleTrail
```
**範例 2：暫停記錄在目前 shell 預設 （在此案例中為法蘭克福 (eu-central-1) 區域） 以外區域中建立之線索的 AWS API 呼叫和日誌檔案交付。**  

```
Stop-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [StopLogging](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `UpdateTrail` 與 CLI
<a name="cloudtrail_example_cloudtrail_UpdateTrail_section"></a>

下列程式碼範例示範如何使用 `UpdateTrail`。

------
#### [ CLI ]

**AWS CLI**  
**更新追蹤記錄**  
下列 `update-trail` 範例會更新追蹤記錄，以使用日誌交付的現有儲存貯體。  

```
aws cloudtrail update-trail \
    --name Trail1 \
    --s3-bucket-name amzn-s3-demo-bucket
```
輸出：  

```
{
    "IncludeGlobalServiceEvents": true,
    "Name": "Trail1",
    "TrailARN": "arn:aws:cloudtrail:us-west-2:123456789012:trail/Trail1",
    "LogFileValidationEnabled": false,
    "IsMultiRegionTrail": true,
    "S3BucketName": "amzn-s3-demo-bucket"
}
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [UpdateTrail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/update-trail.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：更新指定的追蹤，以便記錄全域服務事件 (例如來自 IAM 的事件)，並將後續日誌檔的常見金鑰字首變更為 'globallogs'。**  

```
Update-CTTrail -Name "awscloudtrail-example" -IncludeGlobalServiceEvents $true -S3KeyPrefix "globallogs"
```
**範例 2：更新指定的追蹤，以便將新日誌交付的通知傳送至指定的 SNS 主題。**  

```
Update-CTTrail -Name "awscloudtrail-example" -SnsTopicName "mlog-deliverytopic2"
```
**範例 3：更新指定的追蹤，以便將日誌傳送到不同的儲存貯體。**  

```
Update-CTTrail -Name "awscloudtrail-example" -S3BucketName "otherlogs"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [UpdateTrail](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：更新指定的追蹤，以便記錄全域服務事件 (例如來自 IAM 的事件)，並將後續日誌檔的常見金鑰字首變更為 'globallogs'。**  

```
Update-CTTrail -Name "awscloudtrail-example" -IncludeGlobalServiceEvents $true -S3KeyPrefix "globallogs"
```
**範例 2：更新指定的追蹤，以便將新日誌交付的通知傳送至指定的 SNS 主題。**  

```
Update-CTTrail -Name "awscloudtrail-example" -SnsTopicName "mlog-deliverytopic2"
```
**範例 3：更新指定的追蹤，以便將日誌傳送到不同的儲存貯體。**  

```
Update-CTTrail -Name "awscloudtrail-example" -S3BucketName "otherlogs"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateTrail](https://docs.aws.amazon.com/powershell/v5/reference)。

------