Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

captureWarnings set to True doesn't capture warnings

Tags:

python

logging

I would like to log all warnings. I thought that setting captureWarnings to True should do the trick, but it doesn't. Code:

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__)

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

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

My expectation is that 'Warning test' should appear in test.log, but it doesn't; only 'Test' is put in the log file.

How to capture all warnings and redirect them to the log file?

like image 529
LAdas Avatar asked Jul 22 '16 16:07

LAdas


People also ask

How do you use warnings in Python?

Warning Functions In the above program warnings are displayed using the warn() function of warning module. filterwarnings(action, message=”, category=Warning, module=”, lineno=0, append=False): This function adds an entry into the specifications of the warnings filter. # of the warnings filter. warnings.

How do you raise a warning in Python?

Python programmers issue warnings by calling the warn() function defined in this module. (C programmers use PyErr_WarnEx() ; see Exception Handling for details). Warning messages are normally written to sys.

What does logging getLogger (__ Name __) do?

getLogger(name) is typically executed. The getLogger() function accepts a single argument - the logger's name. It returns a reference to a logger instance with the specified name if provided, or root if not. Multiple calls to getLogger() with the same name will return a reference to the same logger object.


2 Answers

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!

like image 99
cdonts Avatar answered Oct 08 '22 07:10

cdonts


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.

like image 4
user2357112 supports Monica Avatar answered Oct 08 '22 07:10

user2357112 supports Monica