Skip to content

Instantly share code, notes, and snippets.

@ottokruse
Last active June 19, 2020 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ottokruse/6752ef0e5a4e898da27bd1edc5ac987a to your computer and use it in GitHub Desktop.
Save ottokruse/6752ef0e5a4e898da27bd1edc5ac987a to your computer and use it in GitHub Desktop.
AWS Simple Logger (for when you know logs will be sent to CloudWatch Logs)
"""
Logging utility for logging to CloudWatch Logs, to use in e.g. AWS Lambda.
Some small features included:
- log structured JSON as that works really well with CloudWatch Logs filters and CloudWatch Logs Insights
- support turning any Python object into JSON
- replace line endings for nice folding of entries in CloudWatch Logs
- do not buffer stdout
"""
import json
class SimpleLogger:
"""SimpleLogger for logging to CloudWatch Logs.
Does not filter by LogLevel, but instead logs everything to CloudWatch.
Logs can be filtered by level easily when querying in CloudWatch Logs
>>> logger = SimpleLogger("MyLoggerName")
>>> logger.info("my message", event={"test": 123}, another_field="foo")
{
"logger": "MyLoggerName",
"level": "INFO",
"message": "my message",
"event": {
"test": 123
},
"another_field": "foo"
}
"""
def __init__(self, name: str):
self.name = name
def _log(self, level, message: str, **kwargs):
# No need to include a timestamp as CloudWatch Logs assigns one already
self.fields = {
"logger": self.name,
"level": level,
"message": message,
}
self.fields.update(kwargs)
# Dump to JSON (convert non-JSON-able objects to str)
# Replace line endings
# Flush to stdout immediately (no need to set PYTHONUNBUFFERED)
print(
json.dumps(self.fields, indent=2, default=str).replace("\n", "\r"),
flush=True,
)
def debug(self, message: str, **kwargs):
self._log("DEBUG", message, **kwargs)
def info(self, message: str, **kwargs):
self._log("INFO", message, **kwargs)
def warn(self, message: str, **kwargs):
self._log("WARN", message, **kwargs)
def error(self, message: str, **kwargs):
self._log("ERROR", message, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment