Logging

Logging is used collect diagnostic information from a program in case you need to debug or analyze its execution later. Logging is conceptually similar to adding print statements to your code, but with more fine-grained control. In Python, the logging module provides an entry point to generate log messages:


import logging


logging.basicConfig(filename='debug.log', level=logging.DEBUG)


def factorial(n=10):
    """Calculates factorials with log messages."""
    i = 1
    factorial = 1
    while i < n:
        logging.info('starting iteration {}'.format(i))
        factorial *= i
        logging.debug('new factorial: {}'.format(factorial))
        i += 1
    logging.warning('Final result: {}'.format(factorial))


if __name__ == '__main__':
    logging.warning('this is a warning message')
    factorial(10)
    logging.critical('Factorial calculation ended')

Multiple Loggers

It is possible to create multiple loggers with different output channels, like screen, file or HTTP services. Each of them can be configured individually. Some of the options of the logging module include:

option

description

level

order of precedence

filename

where to save the log-messages

format

string that specifies what the message looks like

filter

more sophisticated filtering than with levels only

Whether you need multiple loggers or not, the code example below contains a few ways to customize your log messages:

import logging
import sys

# write log messages to text file and standard output
log = logging.getLogger('example logger')
log.setLevel(logging.INFO)

fmt='%(asctime)s | %(message)s'
format = logging.Formatter(fmt, datefmt='%m/%d/%Y %I:%M:%S %p')

handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(format)
log.addHandler(handler)

handler2 = logging.FileHandler('logfile.log', mode='w')
handler2.setFormatter(format)
log.addHandler(handler2)

log.info('message from logger ')
log.warning('message from logger 2')
log.error('an error has occured')