Python

Table Of Contents

Logging

import queue
from logging import getLogger, StreamHandler, Formatter, DEBUG
from logging.handlers import RotatingFileHandler, QueueHandler, QueueListener

fmt = '%(asctime)s %(levelname)s %(name)s :%(message)s'
stream_handler = StreamHandler()
stream.handler.setFormatter(Formatter(fmt))
stream_handler.setLevel(DEBUG)

file_handler = RotatingFileHandler(filename='log.txt', maxBytes=1024 * 1024, backupCount=10240)
file_handler.setFormatter(Formatter(fmt))
file_handler.setLevel(DEBUG)

stream_queue = queue.Queue(-1)
stream_queue_handler = QueueHandler(stream_queue)
stream_listener = QueueListener(stream_queue, stream_handler)
stream_listner.start()

file_queue = queue.Queue(-1)
file_queue_handler = QueueHandler(file_queue)
file_listener = QueueListener(file_queue, file_handler)
file_listner.start()

def get_logger(name):
    logger = getLogger(name)
    logger.setLevel(DEBUG)
    logger.addHandler(stream_handler)
    logger.addHandler(file_queue_handler)
    logger.propagate = False

    return logger
import logging_util

logger = logging_util.get_logger(__name__)
Comments