Skip to content

Instantly share code, notes, and snippets.

@heitorlessa
Last active July 3, 2022 23:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heitorlessa/cc36ca86c26ce83eec855b9c250b9e1c to your computer and use it in GitHub Desktop.
Save heitorlessa/cc36ca86c26ce83eec855b9c250b9e1c to your computer and use it in GitHub Desktop.
powertools_issue_409

With Pytest and Lambda Powertools installed, run the following command to have human readable and highlighted log statements including stack traces:

POWERTOOLS_LOG_DEDUPLICATION_DISABLED="1" pytest -o log_cli=1 prod_no_swap.py

Output should look like this:

image

2021-05-13 19:05:25,506+0200 — INFO — main:32 — Hello - {'context': {'device_id': '11e9034354f', 'device_location': 'London'}} - -
2021-05-13 19:05:25,507+0200 — ERROR — main:36 — Log stacktrace... - {} - ZeroDivisionError - Traceback (most recent call last):
File "prod.py", line 34, in main
1 / 0
ZeroDivisionError: division by zero
from typing import Dict
import logging
import os
from aws_lambda_powertools import Logger
from aws_lambda_powertools.logging.formatter import LambdaPowertoolsFormatter
class LocalPlainFormatter(LambdaPowertoolsFormatter):
def serialize(self, log: Dict) -> str:
timestamp = log.pop("timestamp", "")
level = log.pop("level", "")
funcNameLoc = log.pop("location", "")
message = log.pop("message", "")
exception = log.pop("exception", "")
exception_name = log.pop("exception_name", "")
extras = log
return f"{timestamp} — {level} — {funcNameLoc} — {message} - {extras} - {exception_name} - {exception}"
# use local formatter and local file only when PT_409 flag is set
has_flag = os.getenv("PT_409")
file_handler = logging.FileHandler("log.txt") if has_flag else None
formatter = LocalPlainFormatter() if has_flag else None
LOGGER = Logger(datefmt="%Y-%m-%dT%H:%M:%SZ", logger_formatter=formatter, logger_handler=file_handler)
def main():
LOGGER.info("Hello")
try:
1 / 0
except ZeroDivisionError:
LOGGER.exception("Log stacktrace...")
if __name__ == "__main__":
main()
from aws_lambda_powertools import Logger
LOGGER = Logger(datefmt="%Y-%m-%dT%H:%M:%SZ")
def main():
LOGGER.info("Hello")
try:
1 / 0
except ZeroDivisionError:
LOGGER.exception("Log stacktrace...")

Export custom flag PT_409 when running locally to log in plain text and write output into log.txt file

PT_409="1" python prod.py 

Output should look like this:

2021-05-13 19:05:25,506+0200 — INFO — main:32 — Hello - {'context': {'device_id': '11e9034354f', 'device_location': 'London'}} -  - 
2021-05-13 19:05:25,507+0200 — ERROR — main:36 — Log stacktrace... - {} - ZeroDivisionError - Traceback (most recent call last):
  File "prod.py", line 34, in main
    1 / 0
ZeroDivisionError: division by zero

import prod
def test_main_logger():
prod.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment