[docs] logging.Logger.debug example doesn't work

Robert Xiao nneonneo at gmail.com
Tue Jul 12 19:45:37 CEST 2011


The Logger.debug example (at
http://docs.python.org/py3k/library/logging.html#logging.Logger.debug) does
not actually work in Python 3.2:

Python 3.2 (r32:88452, Feb 20 2011, 11:12:31)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
>>> logging.basicConfig(format=FORMAT)
>>> d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
>>> logging.warning('Protocol problem: %s', 'connection reset', extra=d)
Traceback (most recent call last):
  File
"/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/logging/__init__.py",
line 934, in emit
    msg = self.format(record)
  File
"/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/logging/__init__.py",
line 809, in format
    return fmt.format(record)
  File
"/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/logging/__init__.py",
line 551, in format
    s = self.formatMessage(record)
  File
"/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/logging/__init__.py",
line 520, in formatMessage
    return self._style.format(record)
  File
"/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/logging/__init__.py",
line 371, in format
    return self._fmt % record.__dict__
KeyError: 'asctime'
Logged from file <stdin>, line 1

The problem is that the logger expects to see the exact string "%(asctime)s"
in the format string before it will add the asctime attribute. Using the
"-15" modifier on the asctime causes the match to fail, and the asctime
attribute is not emitted. To fix the example, change %(asctime)-15s to
%(asctime)s:

Python 3.2 (r32:88452, Feb 20 2011, 11:12:31)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> FORMAT = '%(asctime)s %(clientip)s %(user)-8s %(message)s'
>>> logging.basicConfig(format=FORMAT)
>>> d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
>>> logger = logging.getLogger('tcpserver')
>>> logger.warning('Protocol problem: %s', 'connection reset', extra=d)
2011-07-12 13:39:44,317 192.168.0.1 fbloggs  Protocol problem: connection
reset

This also reflects a problem in the library in that it is not flexible
enough to understand different formats. As a separate matter, perhaps the
library could be amended to always include the asctime field (the asctime
string could be lazily computed by using a class instance for which the
__str__ method produces the actual formatted date), rather than trying to
guess when it is needed.

Robert
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/docs/attachments/20110712/5a14c24a/attachment.html>


More information about the docs mailing list