Modifying logging message format based on message logging level in Python3

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

    Cross-posting of another answer. It doesn't work because of the new (3.2+, 3.4 as of now) implementation of logging.Formatter which now relies on formatting styles. This relies on the '{' style format, but it can be adapted. Could be refined to be more general and allow selection of formatting style and custom messages as arguments to __init__, too.

    class SpecialFormatter(logging.Formatter):
        FORMATS = {logging.DEBUG : logging._STYLES['{']("{module} DEBUG: {lineno}: {message}"),
               logging.ERROR : logging._STYLES['{']("{module} ERROR: {message}"),
               logging.INFO : logging._STYLES['{']("{module}: {message}"),
               'DEFAULT' : logging._STYLES['{']("{module}: {message}")}
    
        def format(self, record):
            # Ugly. Should be better
            self._style = self.FORMATS.get(record.levelno, self.FORMATS['DEFAULT'])
            return logging.Formatter.format(self, record)
    
    hdlr = logging.StreamHandler(sys.stderr)
    hdlr.setFormatter(SpecialFormatter())
    logging.root.addHandler(hdlr)
    logging.root.setLevel(logging.INFO)
    

提交回复
热议问题