在最新版本的 Python 中,会打印您想要的信息。考虑以下脚本logex.py
:
import logging
logger = logging.getLogger(__name__)
def test():
logger.debug('The result is ', 'abc')
def main():
test()
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
main()
当使用 Python 2.7 运行时:
$ python logex.py
Traceback (most recent call last):
File "/usr/lib/python2.7/logging/__init__.py", line 842, in emit
msg = self.format(record)
File "/usr/lib/python2.7/logging/__init__.py", line 719, in format
return fmt.format(record)
File "/usr/lib/python2.7/logging/__init__.py", line 464, in format
record.message = record.getMessage()
File "/usr/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 logex.py, line 6
使用 Python 3.2:
$ python3.2 logex.py
Traceback (most recent call last):
File "/usr/lib/python3.2/logging/__init__.py", line 937, in emit
msg = self.format(record)
File "/usr/lib/python3.2/logging/__init__.py", line 812, in format
return fmt.format(record)
File "/usr/lib/python3.2/logging/__init__.py", line 551, in format
record.message = record.getMessage()
File "/usr/lib/python3.2/logging/__init__.py", line 319, in getMessage
msg = msg % self.args
TypeError: not all arguments converted during string formatting
Logged from file logex.py, line 6
因此,除非您使用的是旧版本的 Python,否则您不必使用 Claudiu 回答中建议的任何技巧。