多进程写日志

import logging
from cloghandler import ConcurrentRotatingFileHandler

import os


class ColoredFormatter(logging.Formatter):
    def __init__(self, fmt=None):
        logging.Formatter.__init__(self, fmt=fmt)

    def format(self, record):
        COLORS = {
            'Black': '0;30',
            'Red': '0;31',
            'Green': '0;32',
            'Brown': '0;33',
            'Blue': '0;34',
            'Purple': '0;35',
            'Cyan': '0;36',
            'Light_Gray': '0;37',

            'Dark_Gray': '1;30',
            'Light_Red': '1;31',
            'Light_Green': '1;32',
            'Yellow': '1;33',
            'Light_Blue': '1;34',
            'Light_Purple': '1;35',
            'Light_Cyan': '1;36',
            'White': '1;37',
        }
        COLOR_SEQ = "\033[%sm"
        RESET_SEQ = "\033[0m"

        message = logging.Formatter.format(self, record)

        if record.levelno == logging.DEBUG:
            message = COLOR_SEQ % COLORS['White'] + message + RESET_SEQ
        elif record.levelno == logging.INFO:
            message = COLOR_SEQ % COLORS['Green'] + message + RESET_SEQ
            pass
        elif record.levelno == logging.WARNING:
            message = COLOR_SEQ % COLORS['Brown'] + message + RESET_SEQ
        elif record.levelno == logging.ERROR:
            message = COLOR_SEQ % COLORS['Red'] + message + RESET_SEQ
        elif record.levelno == logging.CRITICAL:
            message = COLOR_SEQ % COLORS['Purple'] + message + RESET_SEQ
        return message


import logging.handlers


def get_logger(log_name="",
               log_path='logs',
               single_log_file_size=1024  * 1024 * 500,
               log_to_file=True,
               backup_count=1):
    """:return a logger"""

    if not os.path.exists(log_path):
        try:
            os.makedirs(log_path)
        except Exception as e:
            print(str(e))

    logger = logging.getLogger("{}".format(log_name))
    logger.setLevel(logging.DEBUG)

    if log_name and log_to_file:
        # file
        log_file = "{}/{}.log".format(log_path, log_name)
        fh = logging.handlers.ConcurrentRotatingFileHandler(log_file, maxBytes=single_log_file_size, backupCount=backup_count)
        color_formatter = ColoredFormatter(fmt='%(asctime)s %(funcName)s[line:%(lineno)d] [%(levelname)s]: %(message)s')
        fh.setFormatter(color_formatter)
        fh.setLevel(logging.DEBUG)
        logger.addHandler(fh)

    # stdout
    sh = logging.StreamHandler()
    color_formatter = ColoredFormatter(fmt='%(asctime)s %(funcName)s[line:%(lineno)d] [%(levelname)s]: %(message)s')
    sh.setFormatter(color_formatter)
    sh.setLevel(logging.DEBUG)
    logger.addHandler(sh)

    return logger


# logger = get_logger("app.log", '/tmp/api_service')
logger = get_logger("app.log")

if __name__ == '__main__':
    while True:
        logger.info(f"{list(range(300000,400000))}")
posted @ 2019-03-25 17:04  公众号python学习开发  阅读(553)  评论(0编辑  收藏  举报