Skip to content

Instantly share code, notes, and snippets.

@hassaku63
Created February 25, 2021 01:59
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 hassaku63/9f8f5afc354fc5f9a0e29da08b6788d1 to your computer and use it in GitHub Desktop.
Save hassaku63/9f8f5afc354fc5f9a0e29da08b6788d1 to your computer and use it in GitHub Desktop.
JSON Logger example
import os
import json
import logging
from unittest.mock import Mock
LOG_LEVEL = os.environ.get('LOG_LEVEL', 'DEBUG').upper()
if not (LOG_LEVEL in ('DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'CRITICAL', 'FATAL')):
raise ValueError(f'Invalid LOG_LEVEL {LOG_LEVEL}')
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord):
rdict = vars(record)
if isinstance(rdict['msg'], Mock):
rdict['msg'] = repr(rdict['msg'])
return json.dumps(rdict)
def get_logger(name, level=None) -> logging.Logger:
if level is None:
level = LOG_LEVEL
log = logging.getLogger(name)
log.setLevel(level)
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
log.addHandler(handler)
return log
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment