[issue20918] LogRecord.__init__ should handle exception if % operation fails

Vinay Sajip report at bugs.python.org
Fri Mar 14 09:51:38 CET 2014


Vinay Sajip added the comment:

I've looked into it further, and IMO this is not a bug. The rationale is this: when an exception is raised during logging, it is passed to a
handleError method, see

http://hg.python.org/cpython/file/67ada6ab7fe2/Lib/logging/__init__.py#l786

This swallows the exception if logging.raiseExceptions is false or if there is no sys.stderr, otherwise it just writes the original traceback to sys.stderr and ignores any I/O errors which result during that write.

ISTM RDM's analysis is not quite right: logging doesn't try to re-print the arguments. The key indicator is the line

Logged from file <stdin>, line 1

which appears in the traceback shown, indicating that there is no exception in the handleError method itself.

The suggestion by the.mulhern is also based on an incorrect assumption: logging applies the formatting lazily (i.e. late, rather than early), so it would be premature to do anything in LogRecord.__init__. The exception-causing code is called after determining that the record must be processed, and a formatter is asked to format it. This is by design. Note that logging doesn't crash: if the script

class Junk:
    def __repr__(self):
        raise AttributeError('junk')

import logging; logging.warning('%r', Junk())
print('Done.')

is run, it prints

Traceback (most recent call last):
  File "/home/vinay/projects/python/2.7/Lib/logging/__init__.py", line 851, in emit
    msg = self.format(record)
  File "/home/vinay/projects/python/2.7/Lib/logging/__init__.py", line 724, in format
    return fmt.format(record)
  File "/home/vinay/projects/python/2.7/Lib/logging/__init__.py", line 464, in format
    record.message = record.getMessage()
  File "/home/vinay/projects/python/2.7/Lib/logging/__init__.py", line 328, in getMessage
    msg = msg % self.args
  File "logtest3.py", line 3, in __repr__
    raise AttributeError('junk')
AttributeError: junk
Logged from file logtest3.py, line 5
Done.

That last "Done." shows that logging keeps going: while it prints the exception traceback to sys.stderr (so it looks like it's failing) it is not actually failing, and the code after the logging call continues normally even if there is a formatting failure (or other exception during emission of a logging message).

Closing as invalid, unless you come up with something else :-)

----------
assignee:  -> vinay.sajip
resolution:  -> invalid
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue20918>
_______________________________________


More information about the Python-bugs-list mailing list