Watchtower (Python CloudWatch Logging)

3.4.0 · active · verified Sun Mar 29

Watchtower is a log handler for Amazon Web Services (AWS) CloudWatch Logs. It acts as a lightweight adapter between the Python `logging` system and CloudWatch Logs, using the `boto3` AWS SDK to aggregate logs into batches and send them to AWS. It is currently at version 3.4.0 and sees regular, although not strictly scheduled, releases with bug fixes and new features.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate Watchtower with the Python `logging` module to send logs to AWS CloudWatch. It sets up a basic logger and a `CloudWatchLogHandler`, then sends a few example log messages. Ensure your AWS credentials and default region are configured either via environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`) or through the AWS CLI (`aws configure`) for `boto3` to automatically pick them up.

import logging
import os
from watchtower import CloudWatchLogHandler

# Configure basic logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Set AWS credentials via environment variables for boto3 (e.g., AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION)
# Or configure AWS CLI (aws configure) for boto3 to pick up credentials automatically

# Create a CloudWatchLogHandler instance
# Recommended: specify log_group_name and region_name explicitly
# boto3 will automatically pick up credentials from env vars or IAM roles.
handler = CloudWatchLogHandler(
    log_group_name=os.environ.get('AWS_LOG_GROUP', 'my-python-app'),
    region_name=os.environ.get('AWS_REGION', 'us-east-1')
)

# Add the handler to the logger
logger.addHandler(handler)

# Log some messages
logger.info('Hello from Watchtower!')
logger.warning('This is a warning message.')
logger.error(dict(error_code=500, message='Something went wrong'))

# For applications that might exit quickly, ensure logs are flushed
# In typical web applications or long-running services, this is handled on shutdown.
handler.flush()

view raw JSON →