Python: Logging TypeError: not all arguments converted during string formatting

后端 未结 4 1221
独厮守ぢ
独厮守ぢ 2020-12-14 14:55

Here is what I am doing

>>> import logging
>>> logging.getLogger().setLevel(logging.INFO)
>>> from datetime import date
>>&g         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 15:23

    Martijn's answer is correct, but if you prefer to use new style formatting with logging, it can be accomplished by subclassing Logger.

    import logging
    
    class LogRecord(logging.LogRecord):
        def getMessage(self):
            msg = self.msg
            if self.args:
                if isinstance(self.args, dict):
                    msg = msg.format(**self.args)
                else:
                    msg = msg.format(*self.args)
            return msg
    
    class Logger(logging.Logger):
        def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
            rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func)
            if extra is not None:
                for key in extra:
                    rv.__dict__[key] = extra[key]
            return rv
    

    Then just set the logging class:

    logging.setLoggerClass(Logger)
    

提交回复
热议问题