How can I format warnings recorded using logging.captureWarnings?

I used the following code to register alerts:

import logging logging.captureWarnings(True) formatter = logging.Formatter('%(asctime)s\t%(levelname)s\t%(message)s') console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) console_handler.setFormatter(formatter) 

This works, however, my write formatter is not applied, and the warnings are as follows:

 WARNING:py.warnings:/home/joakim/.virtualenvs/masterload/local/lib/python2.7/site-packages/MySQL_python-1.2.3c1-py2.7-linux-x86_64.egg/MySQLdb/cursors.py:100: Warning: InnoDB: ROW_FORMAT=DYNAMIC requires innodb_file_per_table. 

instead of the expected format:

 2012-11-12 18:19:44,421 INFO START updating products 

How can I apply standard formatting to recorded warning messages?

+6
source share
3 answers

You created a handler, but you never configured a logging module to use it:

 console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) console_handler.setFormatter(formatter) 

You need to add this handler to the registrar; root registrar, for example:

 logging.getLogger().addHandler(console_handler) 

Alternatively, you can add a handler only to the alert logger; the captureWarnings() documentation states that it uses py.warnings for captured warnings:

 logging.getLogger('py.warnings').addHandler(console_handler) 

Instead of explicitly creating a handler and formatting, you can also just call basicConfig() to configure the root logger:

 logging.basicConfig(format='%(asctime)s\t%(levelname)s\t%(message)s', level=logging.DEBUG) 

The above basic configuration is the moral equivalent of the handler configuration you created.

+5
source

logging.captureWarnings written to a log called py.warnings , so you need to add a handler to this logger:

 import logging logging.captureWarnings(True) formatter = logging.Formatter('%(asctime)s\t%(levelname)s\t%(message)s') console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) console_handler.setFormatter(formatter) py_warnings_logger = logging.getLogger('py.warnings') py_warnings_logger.addHandler(console_handler) 
+3
source

All Articles