{"id":5880,"library":"cloudwatch","title":"A small handler for AWS Cloudwatch","description":"The `cloudwatch` library (by labrixdigital) provides a lightweight Python logging handler designed to send log events to AWS CloudWatch. It is particularly useful for applications running outside of AWS, on EC2 instances where AWS doesn't log automatically, or when custom log separation is desired. The current version is 1.2.1, with releases occurring infrequently, as its last update was in September 2023.","status":"active","version":"1.2.1","language":"en","source_language":"en","source_url":"https://github.com/labrixdigital/cloudwatch","tags":["aws","cloudwatch","logging","handler","boto3"],"install":[{"cmd":"pip install cloudwatch","lang":"bash","label":"Install with pip"}],"dependencies":[{"reason":"Required for interacting with AWS CloudWatch Logs API.","package":"boto3","optional":false}],"imports":[{"note":"The `cloudwatch` package itself contains the `cloudwatch` module from which `CloudwatchHandler` is imported.","symbol":"CloudwatchHandler","correct":"from cloudwatch import cloudwatch; handler = cloudwatch.CloudwatchHandler(...)"}],"quickstart":{"code":"import logging\nimport os\nfrom cloudwatch import cloudwatch\n\n# Configure AWS credentials from environment variables\naws_access_key_id = os.environ.get('AWS_ACCESS_KEY_ID', 'YOUR_AWS_ACCESS_KEY_ID')\naws_secret_access_key = os.environ.get('AWS_SECRET_ACCESS_KEY', 'YOUR_AWS_SECRET_ACCESS_KEY')\naws_region_name = os.environ.get('AWS_REGION', 'us-east-1') # e.g., 'us-east-1'\n\n# Create a logger\nlogger = logging.getLogger('my_app_logger')\nlogger.setLevel(logging.INFO)\n\n# Create a formatter\nformatter = logging.Formatter('%(asctime)s : %(levelname)s - %(message)s')\n\n# Create the CloudwatchHandler\n# For log_group and log_stream, provide meaningful names for your application\ntry:\n    handler = cloudwatch.CloudwatchHandler(\n        log_group='my-application-logs',\n        log_stream='instance-1',\n        access_key_id=aws_access_key_id,\n        secret_access_key=aws_secret_access_key,\n        region_name=aws_region_name,\n        overflow='truncate' # Options: 'error', 'truncate', 'split'\n    )\n    handler.setFormatter(formatter)\n    logger.addHandler(handler)\n\n    # Use the logger\n    logger.info(\"Application started successfully.\")\n    logger.warning(\"A potential issue was detected.\")\n    logger.error(\"An error occurred during processing.\")\n    print(\"Logs sent to CloudWatch (check AWS console).\")\nexcept Exception as e:\n    print(f\"Failed to send logs to CloudWatch: {e}\")\n    print(\"Please ensure AWS credentials and region are correctly configured.\")\n","lang":"python","description":"This quickstart demonstrates how to integrate the `cloudwatch.CloudwatchHandler` with Python's standard `logging` module. It sets up a logger to send INFO, WARNING, and ERROR level messages to a specified AWS CloudWatch log group and stream. Ensure that `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_REGION` environment variables are set, or replace the placeholder strings with actual credentials for local testing. The `overflow` parameter is set to 'truncate' to handle messages larger than 256KB, preventing errors."},"warnings":[{"fix":"Upgrade `boto3` to its latest version: `pip install --upgrade boto3`.","message":"AWS CloudWatch is undergoing a protocol migration from AWS Query to more efficient AWS JSON 1.0 and Smithy RPC v2 CBOR protocols. While `cloudwatch` directly depends on `boto3`, older versions of `boto3` (pre-dating this change) might cause HTTP 500 errors with 'Missing Action' messages when interacting with CloudWatch. Users should ensure their `boto3` installation is up-to-date to avoid these issues.","severity":"breaking","affected_versions":"Dependent on `boto3` versions that predate AWS CloudWatch protocol updates."},{"fix":"Initialize `CloudwatchHandler` with `overflow='truncate'` or `overflow='split'` to automatically handle oversized messages, for example: `cloudwatch.CloudwatchHandler(..., overflow='truncate')`.","message":"AWS CloudWatch Logs has a maximum event size limit of 256 KB. Sending messages larger than this limit can lead to errors. The `cloudwatch.CloudwatchHandler` provides an `overflow` parameter (defaulting to 'error') to manage this. Options include 'error' (raise exception), 'truncate' (cut message to size), or 'split' (divide into multiple parts).","severity":"gotcha","affected_versions":"All versions"},{"fix":"For applications running on AWS Lambda or ECS, consider leveraging AWS's automatic logging to CloudWatch Logs where possible, or evaluate if a custom handler is truly necessary given the environment's characteristics.","message":"This library is designed for flexibility outside managed AWS logging environments. For serverless infrastructures like AWS Lambda or ECS, AWS often handles logging automatically. Using this custom handler in such environments might introduce unnecessary complexity or encounter limitations (e.g., related to asynchronous processes being frozen in Lambda), as AWS's native log handling is often more efficient and integrated.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-14T00:00:00.000Z","next_check":"2026-07-13T00:00:00.000Z"}