Created
February 25, 2021 01:59
-
-
Save hassaku63/9f8f5afc354fc5f9a0e29da08b6788d1 to your computer and use it in GitHub Desktop.
JSON Logger example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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