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

后端 未结 4 1225
独厮守ぢ
独厮守ぢ 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:26

    You cannot use new-style formatting when using the logging module; use %s instead of {}.

    logging.info('date=%s', date)
    

    The logging module uses the old-style % operator to format the log string. See the debug method for more detail.

    If you really want to use str.format() string formatting, consider using custom objects that apply the formatting 'late', when actually converted to a string:

    class BraceMessage(object):
        def __init__(self, fmt, *args, **kwargs):
            self.fmt = fmt
            self.args = args
            self.kwargs = kwargs
    
        def __str__(self):
            return self.fmt.format(*self.args, **self.kwargs)
    
    __ = BraceMessage
    
    logging.info(__('date={}', date))
    

    This is an approach the Python 3 logging module documentation proposes, and it happens to work on Python 2 too.

提交回复
热议问题