diff --git a/common/logging.py b/common/logging.py index c828510ee..02655c8ce 100644 --- a/common/logging.py +++ b/common/logging.py @@ -1,6 +1,7 @@ """ Common logging functionality to be used for multiple apps """ +import json import logging import os @@ -37,6 +38,21 @@ def format(self, record): return fmt_str +class CloudWatchLogFormatterCustom(watchtower.CloudWatchLogFormatter): + """ + Formatter used for loging in CloudWatch. + Compared to CloudWatchLogFormatter it formats string arguments in the message when the message is JSON. + """ + + def format(self, message): + """ + Include level name and dump as JSON. + """ + formatted_message = logging.Formatter.format(self, message) + msg = {"levelname": getattr(message, "levelname"), "msg": formatted_message} + return json.dumps(msg, default=self.json_serialize_default) + + def setup_cw_logging(main_logger): """Setup CloudWatch logging""" logger = get_logger(__name__) @@ -62,7 +78,7 @@ def setup_cw_logging(main_logger): log_group=CFG.cw_aws_log_group, stream_name=CFG.hostname, ) - handler.formatter.add_log_record_attrs = ["levelname"] + handler.setFormatter(CloudWatchLogFormatterCustom()) except ClientError: logger.exception("Unable to enable CloudWatch logging: ") else: # pragma: no cover