Logging variable data with new format string

后端 未结 9 2223
别那么骄傲
别那么骄傲 2020-11-28 03:09

I use logging facility for python 2.7.3. Documentation for this Python version say:

the logging package pre-dates newer formatting options such as str

9条回答
  •  醉酒成梦
    2020-11-28 03:38

    Similar solution to pR0Ps' , wrapping getMessage in LogRecord by wrapping makeRecord (instead of handle in their answer) in instances of Logger that should be new-formatting-enabled:

    def getLogger(name):
        log = logging.getLogger(name)
        def Logger_makeRecordWrapper(name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None):
            self = log
            record = logging.Logger.makeRecord(self, name, level, fn, lno, msg, args, exc_info, func, sinfo)
            def LogRecord_getMessageNewStyleFormatting():
                self = record
                msg = str(self.msg)
                if self.args:
                    msg = msg.format(*self.args)
                return msg
            record.getMessage = LogRecord_getMessageNewStyleFormatting
            return record
        log.makeRecord = Logger_makeRecordWrapper
        return log
    

    I tested this with Python 3.5.3.

提交回复
热议问题