Skip to content

Commit

Permalink
fix: string formatting in CloudWatch
Browse files Browse the repository at this point in the history
RHINENG-8336
  • Loading branch information
jdobes authored and psegedy committed Jun 20, 2024
1 parent 7e618e9 commit 33a3e53
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion common/logging.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Common logging functionality to be used for multiple apps
"""
import json
import logging
import os

Expand Down Expand Up @@ -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__)
Expand All @@ -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
Expand Down

0 comments on commit 33a3e53

Please sign in to comment.