66

Here is a quick reproduction of the issue:

>>> import logging
>>> logging.getLogger().setLevel(logging.INFO)
>>> from datetime import date
>>> date = date.today()
>>> logging.info('date={}', date)
Traceback (most recent call last):
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 846, in emit
    msg = self.format(record)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 723, in format
    return fmt.format(record)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 464, in format
    record.message = record.getMessage()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 328, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Logged from file <stdin>, line 1
>>> 

How do I make it work?


This is effectively a special case of Why do I get "TypeError: not all arguments converted during string formatting" trying to substitute a placeholder like {0} using %? - but because the actual formatting step happens outside the user's code, different workarounds are necessary.

1
  • In my case, I was trying to pass an exception object to exception level: logger.exception('msg', exception_obj), similar to how I used to pass with error level. Remove the object and let it handle the exception logging for you.
    – whla
    Commented May 4, 2018 at 19:11

5 Answers 5

78

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.

41

You could do the formatting yourself:

logging.info('date={}'.format(date))

As was pointed out by Martijn Pieters, this will always run the string formatting, while using the logging module would cause the formatting to only be performed if the message is actually logged.

2
  • 28
    Do know that by doing the formatting yourself, you loose the speed advantage offered by letting the logging module do it for you only when the message is actually logged. In other words, if you use the debug() handler but the logging level excludes DEBUG level, you are not incurring the penalty of the string formatting operation. The speed difference can be significant if you have a lot of debug messages. Commented Oct 11, 2012 at 16:12
  • I expect heavy calculations even on [logging.debug("my huge structure: %s", json.dumps(my_huge_structure, indent=2))] when debug level is INFO. Its easy to make logging calls wrapper and replace arguments with parameterless lambdas with their calculated values on logging: [wrapper.debug(("my huge structure: %s", lambda: json.dumps(my_huge_structure, indent=2))] Commented Feb 5, 2021 at 12:40
7

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)
1
  • 3
    Or even (at least on Python 3.5) use just LogRecord with logging.setLogRecordFactory(LogRecord) Commented Aug 10, 2016 at 12:32
6

You could do also (Python 3);

logging.info(f'date={date}')
2
  • 3
    It's only for Python 3.6 onwards though. It also evaluates eagerly, while logging module evaluates messages lazily Commented May 24, 2019 at 11:05
  • 1
    ... but all parameters are evaluated even before passing to logging call. Look at my comment above. Commented Feb 5, 2021 at 12:44
0

If you are more familiar with print statements, print directly into logger

logging.info(print("Test:" , variable))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.