logging_details.py

"""
Manage multiple loggers
"""

import logging
import sys


# logger 1: simply writes messages to text file
log1 = logging.getLogger('example1')
log1.addHandler(logging.FileHandler('logger1.log', mode='w'))
log1.addHandler(logging.StreamHandler(sys.stderr))
log1.setLevel(logging.INFO)
log1.info('message for logger 1')


# logger 2: formats timestamp and writes to standard error stream
log2 = logging.getLogger('example2')
handler = logging.StreamHandler(sys.stderr)
log2.addHandler(handler)
fmt='%(asctime)s | MY LOG MESSAGE IS: %(message)s'
handler.setFormatter(logging.Formatter(fmt, datefmt='%m/%d/%Y %I:%M:%S %p'))
log2.setLevel(logging.WARNING)
log2.warning('message for logger 2')

# level of logger 1 is still INFO
log1.info('another message for logger 1')

logging_example.py

"""
the logging module

exercise: change the value of 'level' to
          DEBUG, ERROR, WARNING, INFO and CRITICAL

          find out what is their order of precedence
"""

import logging
import sys

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.info('unhandled event: ' + str(event))
    logging.warning('Final result: {}'.format(factorial))


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


# more loggers to try:

# log = logging.getLogger('example1')
# log.addHandler(logging.FileHandler('debug2.log', mode='w'))
# log.setLevel(logging.DEBUG)
# log.info('spam')

# log2 = logging.getLogger('example2')
# handler = logging.StreamHandler(sys.stderr)
# log2.addHandler(handler)
# fmt='%(asctime)s %(message)s'
# handler.setFormatter(logging.Formatter(fmt, datefmt='%m/%d/%Y %I:%M:%S %p'))
# log2.setLevel(logging.WARNING)
# log2.warning('spam spam spam')

Dr. Kristian Rother

I am a professional Python trainer, developer and author based in Berlin. I believe everybody can learn programming.

Contact me via:
+49 176 3052 4691
krother@academis.eu

Feedback

Thanks, everybody. Without your support... there would be no Spectacular Speaking...

Jerzy Zientkowski, Speakerslair

See also