Created
July 10, 2021 22:43
-
-
Save vikramsoni2/58d7ee1a0691c875e950f6db4ab53b6f to your computer and use it in GitHub Desktop.
logging formats based on log levels
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 logging | |
from bisect import bisect | |
from logging import getLogger, Formatter, LogRecord, StreamHandler | |
from typing import Dict | |
class LevelFormatter(Formatter): | |
def __init__(self, formats: Dict[int, str], **kwargs): | |
super().__init__() | |
if 'fmt' in kwargs: | |
raise ValueError( | |
'Format string must be passed to level-surrogate formatters, ' | |
'not this one' | |
) | |
self.formats = sorted( | |
(level, Formatter(fmt, **kwargs)) for level, fmt in formats.items() | |
) | |
def format(self, record: LogRecord) -> str: | |
idx = bisect(self.formats, (record.levelno,), hi=len(self.formats)-1) | |
level, formatter = self.formats[idx] | |
return formatter.format(record) | |
def test(): | |
handler = StreamHandler() | |
handler.setFormatter( | |
LevelFormatter( | |
{ | |
logging.INFO: '%(levelname)s (info): %(message)s', | |
logging.WARNING: '%(levelname)s: (warning): %(message)s', | |
} | |
) | |
) | |
handler.setLevel(logging.DEBUG) | |
logger = getLogger('test_logger') | |
logger.setLevel(logging.DEBUG) | |
logger.addHandler(handler) | |
logger.debug('mdebug') | |
logger.info('minfo') | |
logger.log(logging.INFO + 1, 'higher minfo') | |
logger.warning('mwarning') | |
logger.error('merror') | |
logger.critical('mcritical') | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment