AWS Logger Python example code snippet

The boto3 library is commonly used for interacting with AWS services, and you can use Python’s built-in logging module to log messages. Here’s a basic example of how you might set up logging in a Python script using the boto3 library:

import logging
import boto3

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Configure AWS credentials and region
aws_access_key_id = 'YOUR_ACCESS_KEY'
aws_secret_access_key = 'YOUR_SECRET_KEY'
region_name = 'YOUR_REGION'

# Create an S3 client
s3 = boto3.client('s3', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name)

# Example logging
logger.info("Connecting to AWS S3...")
try:
    # Example: List all S3 buckets
    response = s3.list_buckets()
    buckets = [bucket['Name'] for bucket in response['Buckets']]
    logger.info(f"S3 Buckets: {buckets}")
except Exception as e:
    logger.error(f"Error: {e}")

In this example:

  • The logging module is configured to log messages at the INFO level or higher.
  • A logger is created using logging.getLogger(name).
  • AWS credentials (access key, secret key) and region are configured.
  • A connection to the S3 service is established using boto3.client.
  • Logging messages are generated using logger.info and logger.error for informational and error messages, respectively.

Remember to replace ‘YOUR_ACCESS_KEY’, ‘YOUR_SECRET_KEY’, and ‘YOUR_REGION’ with your actual AWS credentials and region. Also, ensure that you have the boto3 library installed (pip install boto3). Adjust the logging level and messages based on your specific requirements.