Logging variable data with new format string

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

提交回复
热议问题