captureWarnings set to True doesn't capture warnings

From the logging.captureWarnings documentation:

Warnings issued by the warnings module will be redirected to the logging system. Specifically, a warning will be formatted using warnings.formatwarning() and the resulting string logged to a logger named 'py.warnings' with a severity of WARNING.

You probably want something like this:

import logging
import warnings

from logging.handlers import RotatingFileHandler

logger_file_handler = RotatingFileHandler(u'test.log')
logger_file_handler.setLevel(logging.DEBUG)

logging.captureWarnings(True)

logger = logging.getLogger(__name__)
warnings_logger = logging.getLogger("py.warnings")

logger.addHandler(logger_file_handler)
logger.setLevel(logging.DEBUG)
warnings_logger.addHandler(logger_file_handler)

logger.info(u'Test')
warnings.warn(u'Warning test')

Hope it helps!


logging.captureWarnings is not using your logger. It uses a logger named 'py.warnings'. You will need to configure that logger to do what you want.

Tags:

Python

Logging