Python Logging

Logging in a library

It is strongly advised that you do not add any handlers other than NullHandler to your library’s loggers. This is because the configuration of handlers is the prerogative of the application developer who uses your library. The application developer knows their target audience and what handlers are most appropriate for their application: if you add handlers ‘under the hood’, you might well interfere with their ability to carry out unit tests and deliver logs which suit their requirements.


In [1]:
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())

logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')


WARNING:root:And this, too

Logging in an application

The twelve factor app, an authoritative reference for good practice in application development, contains a section on logging best practice. It emphatically advocates for treating log events as an event stream, and for sending that event stream to standard output to be handled by the application environment.


In [2]:
import logging

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
        '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')


DEBUG:root:debug message
2017-04-19 07:59:50,129 root         DEBUG    debug message
INFO:root:info message
2017-04-19 07:59:50,134 root         INFO     info message
WARNING:root:warn message
2017-04-19 07:59:50,136 root         WARNING  warn message
ERROR:root:error message
2017-04-19 07:59:50,139 root         ERROR    error message
CRITICAL:root:critical message
2017-04-19 07:59:50,143 root         CRITICAL critical message

In [ ]: