Skip to content

Instantly share code, notes, and snippets.

@vadimkantorov
Last active August 29, 2025 21:57
Show Gist options
  • Select an option

  • Save vadimkantorov/97beb2ccd573fa2a6e0f89c5004dc4dd to your computer and use it in GitHub Desktop.

Select an option

Save vadimkantorov/97beb2ccd573fa2a6e0f89c5004dc4dd to your computer and use it in GitHub Desktop.
Logging as jsonl using vanilla Python logging
# https://stackoverflow.com/questions/71944328/how-to-implement-json-format-logs-in-python
import json
import logging
# https://docs.python.org/3/library/logging.html#logrecord-attributes
formatter = type('JsonFormatter', (logging.Formatter, ), dict(format = lambda self, record: json.dumps(dict(time = self.formatTime(record), level = record.levelname, message = record.getMessage(), module = record.module, lineno = record.lineno)) ))()
# simpler version below does not escape quotes in message and does not delete newlines in message
# formatter = logging.Formatter('{\"time\": \"%(asctime)-s\", \"level\": \"%(levelname)-s\", \"message\": \"%(message)s\", \"module\": \"%(module)s\", \"lineno\": %(lineno)d}')
handler_stderr = logging.StreamHandler()
handler_stderr.setFormatter(formatter)
handler_stderr.setLevel(logging.INFO)
logger = logging.getLogger(__name__)
logger.addHandler(handler_stderr)
logger.debug("This is a debug message (will not be shown by console handler).")
logger.info("This is an informational message.")
logger.error("This is an error message.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment