Here is what I am doing
>>> 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
>>>
My python version is
$ python --version
Python 2.7.3
How do I make it work?
You cannot use new-style formatting when using the logging module; use
%s
instead of{}
.The logging module uses the old-style
%
operator to format the log string. See thedebug
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:This is an approach the Python 3
logging
module documentation proposes, and it happens to work on Python 2 too.You could do the formatting yourself:
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.
You could do also (Python 3);
Martijn's answer is correct, but if you prefer to use new style formatting with logging, it can be accomplished by subclassing Logger.
Then just set the logging class: