[Python-Dev] Redirecting warnings.showwarning to logging

Vinay Sajip vinay_sajip at yahoo.co.uk
Tue Nov 25 10:00:43 CET 2008

Based on feedback here, I have a slightly revised proposal. Scott makes the
point that if the file parameter passed in to showwarning is not None, the
caller may be trying to extract output formatting. So, it's not enough just to
assign warnings.showwarning = logging.showwarning, since access to the original
warnings.showwarning may be needed. So, the public API in logging would be

def captureWarnings(capture):
    If capture is true, redirect all warnings to the logging package.
    If capture is False, ensure that warnings are not redirected to logging
    but to their original destinations.

Another new function, _showwarning( message, category, filename, lineno[, file
[, line]]) will be added to the logging package. This implementation of
showwarning will first check to see if the file parameter is None. If a file is
specified, it will delegate to the original warnings implementation of
showwarning. Otherwise, it will call warnings.formatwarning(message, category,
filename, lineno[, line]) and will log the resulting string to a warnings logger
named "py.warnings" [1] with level logging.WARNING. In order to configure
logging of warnings to any particular destination, the logging configuration
code will need to add appropriate handlers to the warnings logger. The precise
format of the logging message will be determined by the logging configuration in
effect, i.e. any formatters configured for the handlers attached to the logger.

I hope this covers everything, but please tell me if that's not the case.


Vinay Sajip

[1] http://mail.python.org/pipermail/python-dev/2004-October/049282.html

More information about the Python-Dev mailing list