Modifying logging message format based on message logging level in Python3

后端 未结 5 1190
天命终不由人
天命终不由人 2021-02-01 06:42

I asked this question for python 2 here, but bumped into the issue again when the the answer no longer worked for Python 3.2.3.

Here\'s code that works on Python 2.7.3:<

5条回答
  •  深忆病人
    2021-02-01 07:08

    I prefer this because it's shorter, simpler and does not require strings like 'ERROR' to be hard coded. No need to reset ._fmt, because else: can handle that just fine.

    Also, using "%(msg)s" doesn't work with lazy logging!

    class Formatter(logging.Formatter):
        def format(self, record):
            if record.levelno == logging.INFO:
                self._style._fmt = "%(message)s"
            else:
                self._style._fmt = "%(levelname)s: %(message)s"
            return super().format(record)
    

    Usage example:

    import logging
    
    logger = logging.getLogger()
    handler = logging.StreamHandler()
    handler.setFormatter(Formatter())
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)
    
    logger.debug('foo')
    logger.info('bar %d', 4)
    
    DEBUG: foo
    bar 4
    

    In case you want to have the levelname colored:

    class Formatter(logging.Formatter):
        def format(self, record):
            if record.levelno == logging.INFO:
                self._style._fmt = "%(message)s"
            else:
                color = {
                    logging.WARNING: 33,
                    logging.ERROR: 31,
                    logging.FATAL: 31,
                    logging.DEBUG: 36
                }.get(record.levelno, 0)
                self._style._fmt = f"\033[{color}m%(levelname)s\033[0m: %(message)s"
            return super().format(record)
    

    see https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit for color numbers

提交回复
热议问题