Logging variable data with new format string

后端 未结 9 1981
别那么骄傲
别那么骄傲 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:35

    Here's something real simple that works:

    debug_logger: logging.Logger = logging.getLogger("app.debug")
    
    def mydebuglog(msg: str, *args, **kwargs):
        if debug_logger.isEnabledFor(logging.DEBUG):
            debug_logger.debug(msg.format(*args, **kwargs))
    

    Then:

    mydebuglog("hello {} {val}", "Python", val="World")
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 03:39

    I created a custom Formatter, called ColorFormatter that handles the problem like this:

    class ColorFormatter(logging.Formatter):
    
        def format(self, record):
            # previous stuff, copy from logging.py…
    
            try:  # Allow {} style
                message = record.getMessage()  # printf
            except TypeError:
                message = record.msg.format(*record.args)
    
            # later stuff…
    

    This keeps it compatible with various libraries. The drawback is that it is probably not performant due to potentially attempting format of the string twice.

    0 讨论(0)
提交回复
热议问题