Controlling exception handling of logging module

S

sj

Suppose the following are part of a long file and executed:

logging.basicConfig(stream = sys.stderr, level=logging.INFO)
logging.info("%d %d", 1, 2, 3) # buggy

Python prints the traceback of the error as follows:

Traceback (most recent call last):
File ".../local/lib/python2.4/logging/__init__.py", line 706, in emit
msg = self.format(record)
File ".../local/lib/python2.4/logging/__init__.py", line 592, in
format
return fmt.format(record)
File ".../local/lib/python2.4/logging/__init__.py", line 382, in
format
record.message = record.getMessage()
File ".../local/lib/python2.4/logging/__init__.py", line 253, in
getMessage
msg = msg % self.args
TypeError: not all arguments converted during string formatting

It tells why error occurred, but the traceback is not helpful to locate
where it occurred. I believe that's because the logging module caught
and ate up the exception. I understand that this is a sensible setting
as logging shouldn't harm the main program, but in the debugging phase,
I really want this exception to propagate up so that I can easily
locate from my code. Is there any way to control this behavior so the
error is not handled by the logging module itself?
 
W

wittempj

make the second statement 'logging.info("%d %d", 1, 2)' or
'logging.info("%d %d %d", 1, 2, 3)', and all works. for every argument
you want to log you need one format specifier
 
S

sj

Thanks, but my point wasn't fixing the bug. I'd like the logging
module to raise an exception on this occasion (rather than print and
consume the error) so that I can find the bug easily. If those two
lines were part of 10,000-line code, I'd have to check all logging
statements one-by-one.
 
V

Vinay Sajip

sj said:
Thanks, but my point wasn't fixing the bug. I'd like the logging
module to raise an exception on this occasion (rather than print and
consume the error) so that I can find the bug easily. If those two
lines were part of 10,000-line code, I'd have to check all logging
statements one-by-one.

You'll need to subclass your handler and redefine handleError(), which
is called when an exception is raised during a handler's emit()
operation. See

http://www.red-dove.com/logging/public/logging.Handler-class.html#handleError
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top