A small handler for AWS Cloudwatch
Slowing down. Last release over 3 years ago, little activity since. Fine for existing code; think twice for a new project.
Consider insteaddatadog-loggerPythie’s Index: 6420.7K downloads/moCompare →
pip install cloudwatchAWS Cloudwatch Lightweight Handler
This small log handler is designed to send events to AWS Cloudwatch. It is useful when operating infrastructure outside of the AWS, when AWS does not log automatically (EC2) or when you want to separate logs. If you are logging on Serverless Infrastructure (e.g. Lambdas or ECS) you might find it easier to just let AWS Handle the logs automatically.
We originally developed this to be used on dedicated servers (on and off EC2) and chose to create something new because we wanted to:
- Be able to provide your own AWS programmatic access credentials
- Have a lightweight solution (only the handler is included and you need only one file)
If you already have a codebase that is using python's logger, you only need minor modifications to send your logs to AWS. In fact, you only need to change code at the logger creation. If you haven't done any logging before, I recommend you look at a basic tutorial on python's logging module. There are plenty of resources out there.
Installing it
We are on PyPi, so you can install via pip
pip install cloudwatch
Or if you prefer to customise and (hopefully) feedback on improvements and bugs
git clone https://github.com/labrixdigital/cloudwatch
Usage
This module is designed to fit right into your existing logging code, so you only need to replace (or add) a handler and the same logger will send events to cloudwatch.
import logging
#Create the logger
logger = logging.getLogger('my_logger')
#Create the formatter
formatter = logging.Formatter('%(asctime)s : %(levelname)s - %(message)s')
#Import cloudwath and create the new handler
from cloudwatch import cloudwatch
handler = cloudwatch.CloudwatchHandler(log_group = 'my_log_group')
#Pass the formater to the handler
handler.setFormatter(formatter)
#Set the level
logger.setLevel(logging.WARNING)
#Add the handler to the logger
logger.addHandler(handler)
#USE IT!
logger.warning("Watch out! Something happened!")
Credentials
Specifying credentials and region
If you dont add credentials when creating the handler, it uses the default AWS credentials that you set-up on the CLI, or that you passed on the invokation (if using on EC2, Lambda, ECS), this is in line with the boto3 configuration Expained here. However, you can also specify the credentials like this:
handler = cloudwatch.CloudwatchHandler(
log_group = 'my_log_group',
access_id = 'AWS_ACCESS_KEY_ID',
access_key = 'AWS_SECRET_ACCESS_KEY'
)