How to get the bucket logging details of a S3 bucket using Boto3 and AWS Client?


Problem Statement − Use boto3 library in Python to get the logging details of a S3 bucket. For example, find the logging details of Bucket_1 in S3.

Approach/Algorithm to solve this problem

Step 1 − Import boto3 and botocore exceptions to handle exceptions.

Step 2 − Use bucket_name as the parameter in the function.

Step 3 − Create an AWS session using boto3 library.

Step 4 − Create an AWS client for S3.

Step 5 − Now use the function get_bucket_logging and pass the bucket name.

Step 6 − It returns the dictionary containing the details about S3.

Step 7 − Handle the generic exception if something went wrong while deleting the file

Example

Use the following code to get the bucket logging details −

import boto3
from botocore.exceptions import ClientError

def get_bucket_logging_of_s3(bucket_name):
   session = boto3.session.Session()
   s3_client = session.client('s3')
   try:
      result = s3_client.get_bucket_logging(Bucket=bucket_name,)
   except ClientError as e:
      raise Exception( "boto3 client error in get_bucket_logging_of_s3: " + e.__str__())
   except Exception as e:
      raise Exception( "Unexpected error in get_bucket_logging_of_s3 function: " + e.__str__())
return result

print(get_bucket_logging_of_s3("Bucket_1"))

Output

{
   'LoggingEnabled': {
      'TargetBucket': 'string',
      'TargetGrants': [
         {
            'Grantee': {
               'DisplayName': 'string',
               'EmailAddress': 'string',
               'ID': 'string',
               'Type': 'CanonicalUser'|'AmazonCustomerByEmail'|'Group',
               'URI': 'string'
            },
            'Permission': 'FULL_CONTROL'|'READ'|'WRITE'
         },
      ],
      'TargetPrefix': 'string'
   }
}

Updated on: 22-Mar-2021

428 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements