

There are more AWS SDK examples available in the [AWS Doc SDK Examples](https://github.com/awsdocs/aws-doc-sdk-examples) GitHub repo.

# Code examples for CloudTrail using AWS SDKs
<a name="cloudtrail_code_examples"></a>

The following code examples show you how to use AWS CloudTrail with an AWS software development kit (SDK).

*Actions* are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios.

**More resources**
+  **[ CloudTrail Developer Guide](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html)** – More information about CloudTrail.
+ **[CloudTrail API Reference](https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/Welcome.html)** – Details about all available CloudTrail actions.
+ **[AWS Developer Center](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-product=product%23)** – Code examples that you can filter by category or full-text search.
+ **[AWS SDK Examples](https://github.com/awsdocs/aws-doc-sdk-examples)** – GitHub repo with complete code in preferred languages. Includes instructions for setting up and running the code.

**Contents**
+ [Basics](cloudtrail_code_examples_basics.md)
  + [Actions](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)

# Basic examples for CloudTrail using AWS SDKs
<a name="cloudtrail_code_examples_basics"></a>

The following code examples show how to use the basics of AWS CloudTrail with AWS SDKs. 

**Contents**
+ [Actions](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)

# Actions for CloudTrail using AWS SDKs
<a name="cloudtrail_code_examples_actions"></a>

The following code examples demonstrate how to perform individual CloudTrail actions with AWS SDKs. Each example includes a link to GitHub, where you can find instructions for setting up and running the code. 

 The following examples include only the most commonly used actions. For a complete list, see the [AWS CloudTrail API Reference](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)

# Use `CreateTrail` with an AWS SDK or CLI
<a name="cloudtrail_example_cloudtrail_CreateTrail_section"></a>

The following code examples show how to use `CreateTrail`.

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

**SDK for C\$1\$1**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](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();
}
```
+  For API details, see [CreateTrail](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/CreateTrail) in *AWS SDK for C\$1\$1 API Reference*. 

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

**AWS CLI**  
**To create a trail**  
The following `create-trail` example creates a multi-region trail named `Trail1` and specifies an S3 bucket.  

```
aws cloudtrail create-trail \
    --name Trail1 \
    --s3-bucket-name amzn-s3-demo-bucket \
    --is-multi-region-trail
```
Output:  

```
{
    "IncludeGlobalServiceEvents": true,
    "Name": "Trail1",
    "TrailARN": "arn:aws:cloudtrail:us-west-2:123456789012:trail/Trail1",
    "LogFileValidationEnabled": false,
    "IsMultiRegionTrail": true,
    "S3BucketName": "amzn-s3-demo-bucket"
}
```
+  For API details, see [CreateTrail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/create-trail.html) in *AWS CLI Command Reference*. 

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

**Tools for PowerShell V4**  
**Example 1: Creates a trail that will use the bucket 'amzn-s3-demo-bucket' for log file storage.**  

```
New-CTTrail -Name "awscloudtrail-example" -S3BucketName "amzn-s3-demo-bucket"
```
**Example 2: Creates a trail that will use the bucket 'amzn-s3-demo-bucket' for log file storage. The S3 objects representing the logs will have a common key prefix of 'mylogs'. When new logs are delivered to the bucket a notification will be sent to the SNS topic 'mlog-deliverytopic'. This example using splatting to supply the parameter values to the cmdlet.**  

```
$params = @{
    Name="awscloudtrail-example"
    S3BucketName="amzn-s3-demo-bucket"
    S3KeyPrefix="mylogs"
    SnsTopicName="mlog-deliverytopic"
}      
New-CTTrail @params
```
+  For API details, see [CreateTrail](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Creates a trail that will use the bucket 'amzn-s3-demo-bucket' for log file storage.**  

```
New-CTTrail -Name "awscloudtrail-example" -S3BucketName "amzn-s3-demo-bucket"
```
**Example 2: Creates a trail that will use the bucket 'amzn-s3-demo-bucket' for log file storage. The S3 objects representing the logs will have a common key prefix of 'mylogs'. When new logs are delivered to the bucket a notification will be sent to the SNS topic 'mlog-deliverytopic'. This example using splatting to supply the parameter values to the cmdlet.**  

```
$params = @{
    Name="awscloudtrail-example"
    S3BucketName="amzn-s3-demo-bucket"
    S3KeyPrefix="mylogs"
    SnsTopicName="mlog-deliverytopic"
}      
New-CTTrail @params
```
+  For API details, see [CreateTrail](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

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

**SDK for Ruby**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](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
```
+  For API details, see [CreateTrail](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/CreateTrail) in *AWS SDK for Ruby API Reference*. 

------

# Use `DeleteTrail` with an AWS SDK or CLI
<a name="cloudtrail_example_cloudtrail_DeleteTrail_section"></a>

The following code examples show how to use `DeleteTrail`.

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

**SDK for C\$1\$1**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](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();
}
```
+  For API details, see [DeleteTrail](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/DeleteTrail) in *AWS SDK for C\$1\$1 API Reference*. 

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

**AWS CLI**  
**To delete a trail**  
The following `delete-trail` command deletes a trail named `Trail1`:  

```
aws cloudtrail delete-trail --name Trail1
```
+  For API details, see [DeleteTrail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/delete-trail.html) in *AWS CLI Command Reference*. 

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

**Tools for PowerShell V4**  
**Example 1: Deletes the specified trail. You will be prompted for confirmation before the command is run. To suppress confirmation, add the -Force switch parameter.**  

```
Remove-CTTrail -Name "awscloudtrail-example"
```
+  For API details, see [DeleteTrail](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Deletes the specified trail. You will be prompted for confirmation before the command is run. To suppress confirmation, add the -Force switch parameter.**  

```
Remove-CTTrail -Name "awscloudtrail-example"
```
+  For API details, see [DeleteTrail](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

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

**SDK for Ruby**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](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
```
+  For API details, see [DeleteTrail](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/DeleteTrail) in *AWS SDK for Ruby API Reference*. 

------

# Use `DescribeTrail` with an AWS SDK
<a name="cloudtrail_example_cloudtrail_DescribeTrail_section"></a>

The following code example shows how to use `DescribeTrail`.

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

**SDK for C\$1\$1**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](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();
}
```
+  For API details, see [DescribeTrail](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/DescribeTrail) in *AWS SDK for C\$1\$1 API Reference*. 

------

# Use `DescribeTrails` with a CLI
<a name="cloudtrail_example_cloudtrail_DescribeTrails_section"></a>

The following code examples show how to use `DescribeTrails`.

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

**AWS CLI**  
**To describe a trail**  
The following `describe-trails` example returns the settings for `Trail1` and `Trail2`.  

```
aws cloudtrail describe-trails \
    --trail-name-list Trail1 Trail2
```
Output:  

```
{
    "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"
        }
    ]
}
```
+  For API details, see [DescribeTrails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/describe-trails.html) in *AWS CLI Command Reference*. 

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

**Tools for PowerShell V4**  
**Example 1: Returns the settings of all trails associated with the current region for your account.**  

```
Get-CTTrail
```
**Example 2: Returns the settings for the specified trails.**  

```
Get-CTTrail -TrailNameList trail1,trail2
```
**Example 3: Returns the settings for the specified trails that were created in a region other than the current shell default (in this case the Frankfurt (eu-central-1) region).**  

```
Get-CTTrail -TrailNameList trailABC,trailDEF -Region eu-central-1
```
+  For API details, see [DescribeTrails](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Returns the settings of all trails associated with the current region for your account.**  

```
Get-CTTrail
```
**Example 2: Returns the settings for the specified trails.**  

```
Get-CTTrail -TrailNameList trail1,trail2
```
**Example 3: Returns the settings for the specified trails that were created in a region other than the current shell default (in this case the Frankfurt (eu-central-1) region).**  

```
Get-CTTrail -TrailNameList trailABC,trailDEF -Region eu-central-1
```
+  For API details, see [DescribeTrails](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `GetTrailStatus` with a CLI
<a name="cloudtrail_example_cloudtrail_GetTrailStatus_section"></a>

The following code examples show how to use `GetTrailStatus`.

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

**AWS CLI**  
**To get the status of a trail**  
The following `get-trail-status` command returns the delivery and logging details for `Trail1`:  

```
aws cloudtrail get-trail-status --name Trail1
```
Output:  

```
{
  "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"
}
```
+  For API details, see [GetTrailStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/get-trail-status.html) in *AWS CLI Command Reference*. 

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

**Tools for PowerShell V4**  
**Example 1: Returns status information for the trail with name 'myExampleTrail'. Returned data includes information on delivery errors, Amazon SNS and Amazon S3 errors, and start and stop logging times for the trail. This example assumes the trail was created in the same region as the current shell default.**  

```
Get-CTTrailStatus -Name myExampleTrail
```
**Example 2: Returns status information for a trail that was created in a region other than the current shell default (in this case, the Frankfurt (eu-central-1) region).**  

```
Get-CTTrailStatus -Name myExampleTrail -Region eu-central-1
```
+  For API details, see [GetTrailStatus](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Returns status information for the trail with name 'myExampleTrail'. Returned data includes information on delivery errors, Amazon SNS and Amazon S3 errors, and start and stop logging times for the trail. This example assumes the trail was created in the same region as the current shell default.**  

```
Get-CTTrailStatus -Name myExampleTrail
```
**Example 2: Returns status information for a trail that was created in a region other than the current shell default (in this case, the Frankfurt (eu-central-1) region).**  

```
Get-CTTrailStatus -Name myExampleTrail -Region eu-central-1
```
+  For API details, see [GetTrailStatus](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `ListTrails` with an AWS SDK
<a name="cloudtrail_example_cloudtrail_ListTrails_section"></a>

The following code example shows how to use `ListTrails`.

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

**SDK for Ruby**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](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
```
+  For API details, see [ListTrails](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/ListTrails) in *AWS SDK for Ruby API Reference*. 

------

# Use `LookupEvents` with an AWS SDK or CLI
<a name="cloudtrail_example_cloudtrail_LookupEvents_section"></a>

The following code examples show how to use `LookupEvents`.

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

**SDK for C\$1\$1**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](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;
}
```
+  For API details, see [LookupEvents](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/LookupEvents) in *AWS SDK for C\$1\$1 API Reference*. 

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

**AWS CLI**  
**To look up events for a trail**  
The following `lookup-events` command looks up API activity events by the attribute `EventName`:  

```
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=ConsoleLogin
```
Output:  

```
{
  "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": []
     }
  ]
}
```
+  For API details, see [LookupEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/lookup-events.html) in *AWS CLI Command Reference*. 

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

**Tools for PowerShell V4**  
**Example 1: Returns all events that have occurred over the last seven days. The cmdlet by default automatically makes multiple calls to deliver all events, exiting when the service indicates no further data is available.**  

```
Find-CTEvent
```
**Example 2: Returns all events that have occurred over the last seven days specifying a region that is not the current shell default.**  

```
Find-CTEvent -Region eu-central-1
```
**Example 3: Returns all events that are associated with the RunInstances API call.**  

```
Find-CTEvent -LookupAttribute @{ AttributeKey="EventName"; AttributeValue="RunInstances" }
```
**Example 4: Returns the first 5 available events.**  

```
Find-CTEvent -MaxResult 5
```
+  For API details, see [LookupEvents](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Returns all events that have occurred over the last seven days. The cmdlet by default automatically makes multiple calls to deliver all events, exiting when the service indicates no further data is available.**  

```
Find-CTEvent
```
**Example 2: Returns all events that have occurred over the last seven days specifying a region that is not the current shell default.**  

```
Find-CTEvent -Region eu-central-1
```
**Example 3: Returns all events that are associated with the RunInstances API call.**  

```
Find-CTEvent -LookupAttribute @{ AttributeKey="EventName"; AttributeValue="RunInstances" }
```
**Example 4: Returns the first 5 available events.**  

```
Find-CTEvent -MaxResult 5
```
+  For API details, see [LookupEvents](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

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

**SDK for Ruby**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](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
```
+  For API details, see [LookupEvents](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/LookupEvents) in *AWS SDK for Ruby API Reference*. 

------

# Use `StartLogging` with a CLI
<a name="cloudtrail_example_cloudtrail_StartLogging_section"></a>

The following code examples show how to use `StartLogging`.

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

**AWS CLI**  
**To start logging for a trail**  
The following `start-logging` command turns on logging for `Trail1`:  

```
aws cloudtrail start-logging --name Trail1
```
+  For API details, see [StartLogging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/start-logging.html) in *AWS CLI Command Reference*. 

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

**Tools for PowerShell V4**  
**Example 1: Starts the recording of AWS API calls and log file delivery for the trail named 'myExampleTrail'. This example assumes the trail was created in the same region as the current shell default.**  

```
Start-CTLogging -Name myExampleTrail
```
**Example 2: Starts the recording of AWS API calls and log file delivery for a trail that was created in a region other than the current shell default (in this case, the Frankfurt (eu-central-1) region).**  

```
Start-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  For API details, see [StartLogging](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Starts the recording of AWS API calls and log file delivery for the trail named 'myExampleTrail'. This example assumes the trail was created in the same region as the current shell default.**  

```
Start-CTLogging -Name myExampleTrail
```
**Example 2: Starts the recording of AWS API calls and log file delivery for a trail that was created in a region other than the current shell default (in this case, the Frankfurt (eu-central-1) region).**  

```
Start-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  For API details, see [StartLogging](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `StopLogging` with a CLI
<a name="cloudtrail_example_cloudtrail_StopLogging_section"></a>

The following code examples show how to use `StopLogging`.

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

**AWS CLI**  
**To stop logging a trail**  
The following `stop-logging` command turns off logging for `Trail1`:  

```
aws cloudtrail stop-logging --name Trail1
```
+  For API details, see [StopLogging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/stop-logging.html) in *AWS CLI Command Reference*. 

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

**Tools for PowerShell V4**  
**Example 1: Suspends the recording of AWS API calls and log file delivery for the trail named 'myExampleTrail'. This example assumes the trail was created in the same region as the current shell default.**  

```
Stop-CTLogging -Name myExampleTrail
```
**Example 2: Suspends the recording of AWS API calls and log file delivery for a trail that was created in a region other than the current shell default (in this case, the Frankfurt (eu-central-1) region).**  

```
Stop-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  For API details, see [StopLogging](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Suspends the recording of AWS API calls and log file delivery for the trail named 'myExampleTrail'. This example assumes the trail was created in the same region as the current shell default.**  

```
Stop-CTLogging -Name myExampleTrail
```
**Example 2: Suspends the recording of AWS API calls and log file delivery for a trail that was created in a region other than the current shell default (in this case, the Frankfurt (eu-central-1) region).**  

```
Stop-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  For API details, see [StopLogging](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------

# Use `UpdateTrail` with a CLI
<a name="cloudtrail_example_cloudtrail_UpdateTrail_section"></a>

The following code examples show how to use `UpdateTrail`.

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

**AWS CLI**  
**To update a trail**  
The following `update-trail` example updates a trail to use an existing bucket for log delivery.  

```
aws cloudtrail update-trail \
    --name Trail1 \
    --s3-bucket-name amzn-s3-demo-bucket
```
Output:  

```
{
    "IncludeGlobalServiceEvents": true,
    "Name": "Trail1",
    "TrailARN": "arn:aws:cloudtrail:us-west-2:123456789012:trail/Trail1",
    "LogFileValidationEnabled": false,
    "IsMultiRegionTrail": true,
    "S3BucketName": "amzn-s3-demo-bucket"
}
```
+  For API details, see [UpdateTrail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/update-trail.html) in *AWS CLI Command Reference*. 

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

**Tools for PowerShell V4**  
**Example 1: Updates the specified trail so that global service events (such as those from IAM) are recorded and changes the common key prefix of the log files going forwards to be 'globallogs'.**  

```
Update-CTTrail -Name "awscloudtrail-example" -IncludeGlobalServiceEvents $true -S3KeyPrefix "globallogs"
```
**Example 2: Updates the specified trail so notifications about new log deliveries are sent to the specified SNS topic.**  

```
Update-CTTrail -Name "awscloudtrail-example" -SnsTopicName "mlog-deliverytopic2"
```
**Example 3: Updates the specified trail so logs are delivered to a different bucket.**  

```
Update-CTTrail -Name "awscloudtrail-example" -S3BucketName "otherlogs"
```
+  For API details, see [UpdateTrail](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS Tools for PowerShell Cmdlet Reference (V4)*. 

**Tools for PowerShell V5**  
**Example 1: Updates the specified trail so that global service events (such as those from IAM) are recorded and changes the common key prefix of the log files going forwards to be 'globallogs'.**  

```
Update-CTTrail -Name "awscloudtrail-example" -IncludeGlobalServiceEvents $true -S3KeyPrefix "globallogs"
```
**Example 2: Updates the specified trail so notifications about new log deliveries are sent to the specified SNS topic.**  

```
Update-CTTrail -Name "awscloudtrail-example" -SnsTopicName "mlog-deliverytopic2"
```
**Example 3: Updates the specified trail so logs are delivered to a different bucket.**  

```
Update-CTTrail -Name "awscloudtrail-example" -S3BucketName "otherlogs"
```
+  For API details, see [UpdateTrail](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS Tools for PowerShell Cmdlet Reference (V5)*. 

------