Modifying logging message format based on message logging level in Python3

后端 未结 5 1274
天命终不由人
天命终不由人 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:06

    For some weird reasons, the solutions of @JS and @Evpok were raising some errors (I am using Python 3.7 and that might be why).

    This solution worked for me:

    class CustomFormatter(logging.Formatter):
        """Logging Formatter to add colors and count warning / errors"""
    
        FORMATS = {
            logging.ERROR: "ERROR: %(msg)s",
            logging.WARNING: "WARNING: %(msg)s",
            logging.DEBUG: "DBG: %(module)s: %(lineno)d: %(msg)s",
            "DEFAULT": "%(msg)s",
        }
    
        def format(self, record):
            log_fmt = self.FORMATS.get(record.levelno, self.FORMATS['DEFAULT'])
            formatter = logging.Formatter(log_fmt)
            return formatter.format(record)
    
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    logger_ch = logging.StreamHandler()
    logger_ch.setLevel(logging.INFO)
    logger_ch.setFormatter(CustomFormatter())
    logger.addHandler(logger_ch)
    

提交回复
热议问题