pyhon logging class code example

Example 1: from logging import logger

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import logging

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)

logger.debug('Loging %s lewel', 'DEBUG')
logger.info('Loging %s lewel', 'INFO')
logger.warning('Loging %s lewel', 'WARN')
logger.error('Loging %s lewel', 'ERROR')
logger.critical('Loging %s lewel', 'CRITICAL')

Example 2: pythong logging logger to string

import logging
try:
    from cStringIO import StringIO      # Python 2
except ImportError:
    from io import StringIO

class LevelFilter(logging.Filter):
    def __init__(self, levels):
        self.levels = levels

    def filter(self, record):
        return record.levelno in self.levels

log_stream = StringIO()    
logging.basicConfig(stream=log_stream, level=logging.NOTSET)
logging.getLogger().addFilter(LevelFilter((logging.INFO, logging.WARNING, logging.ERROR)))

logging.info('hello world')
logging.warning('be careful!')
logging.debug("you won't see this")
logging.error('you will see this')
logging.critical('critical is no longer logged!')

print(log_stream.getvalue())

Tags:

Misc Example