Skip to content

Instantly share code, notes, and snippets.

@ZoeLiao
Last active November 14, 2019 01:03
Show Gist options
  • Save ZoeLiao/8be9ed4d798b54818cc1000ab71899c5 to your computer and use it in GitHub Desktop.
Save ZoeLiao/8be9ed4d798b54818cc1000ab71899c5 to your computer and use it in GitHub Desktop.
Plug your Django application logging directly into AWS CloudWatch by watchtower
import logging
from boto3.session import Session
AWS_ACCESS_KEY_ID = 'your aws key ID'
AWS_SECRET_ACCESS_KEY = 'your aws secret access key'
AWS_REGION_NAME = 'your region name. e.g, us-east-1'
AWS_LOG_GROUP = 'MyLogGroup', # your log group
AWS_LOG_STREAM = 'Mystream', # your stream
AWS_LOGGER_NAME = 'watchtower-logger' # your logger
# logger
boto3_session = Session(
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
region_name=AWS_REGION_NAME
)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'aws': {
# you can add specific format for aws here
# if you want to change format, you can read:
# https://stackoverflow.com/questions/533048/how-to-log-source-file-name-and-line-number-in-python/44401529
'format': u"%(asctime)s [%(levelname)-8s] %(message)s [%(pathname)s:%(lineno)d]",
'datefmt': "%Y-%m-%d %H:%M:%S"
},
},
'handlers': {
'watchtower': {
'level': 'DEBUG',
'class': 'watchtower.CloudWatchLogHandler',
'boto3_session': boto3_session,
'log_group': AWS_LOG_GROUP,
'stream_name': AWS_LOG_STREAM,
'formatter': 'aws', # use custom format
},
},
'loggers': {
AWS_LOGGER_NAME: {
'level': 'DEBUG',
'handlers': ['watchtower'],
'propagate': False,
},
# add your other loggers here...
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment