Modifying logging message format based on message logging level in Python3

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

    I am quiet late for this question but here is my solution. It follows the original python 2 syntax style. In general there are three new classes that you should be using due to the addition of styles support. Those are: PercentStyle, StrFormatStyle, and StringTemplateStyle.

    from logging import Formatter, PercentStyle, ERROR, WARNING, INFO, DEBUG
    class SrvLogFormat(Formatter):
        def __init__(self):
            super().__init__(fmt=env.fmt_log, datefmt=env.fmt_log_date)
    
        def format(self, record):
            original_style = self._style
    
            if record.levelno == DEBUG:
                self._style = PercentStyle(env.fmt_dflt)
            if record.levelno == INFO:
                self._style = PercentStyle(env.fmt_dflt)
            if record.levelno == WARNING:
                self._style = PercentStyle(env.fmt_dflt)
            if record.levelno == ERROR:
                self._style = PercentStyle(env.fmt_err)
    
            result = Formatter.format(self, record)
            self._style = original_style
            return result
    

提交回复
热议问题