自己定义一个python的logging类模块,方便其他程序调用

写于此,方便自己日后查找,直接复制到其他程序中使用

import time
import os
import colorlog
import logging
class MyLogging():
    log_colors_config = {
        'DEBUG': 'white',  # cyan white
        'INFO': 'green',
        'WARNING': 'yellow',
        'ERROR': 'red',
        'CRITICAL': 'bold_red',
    }
    def __init__(self,filename=None,timeInName=False,con_level='warning',file_level='debug'):

        if not os.path.exists('./Logs'):
            os.makedirs('./Logs')
        if filename==None:
            filename = './Logs/' + time.strftime('%Y-%m-%d %H_%M_%S',time.localtime(time.time())) + '.log'
        else:
            if timeInName:
                filename = './Logs/' + time.strftime('%Y-%m-%d %H_%M_%S',time.localtime(time.time())) + '-' + filename + '.log'
            else:
                filename = './Logs/' + filename + '.log'

        self.logger = logging.getLogger('my_log')
        self.logger.setLevel(logging.DEBUG)

        #处理器Hander
        consoleHander = logging.StreamHandler()
        consoleHander.setLevel(self.get_level(con_level))

        #不指定输出级别则采用logger的级别,都设置了则取最低级
        fileHander = logging.FileHandler(filename=filename)
        fileHander.setLevel(self.get_level(file_level))

        #formatter格式
        formatter1 = logging.Formatter("%(asctime)s | %(levelname)s | %(filename)s - %(funcName)s : %(lineno)s | %(message)s")
        formatter2 = colorlog.ColoredFormatter(fmt='%(log_color)s[%(asctime)s.%(msecs)03d] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s',
                                               log_colors=self.log_colors_config)

        #给处理器设置格式
        consoleHander.setFormatter(formatter2)
        fileHander.setFormatter(formatter1)

        #记录器设置处理器
        self.logger.addHandler(consoleHander)
        self.logger.addHandler(fileHander)
    def get_level(self,level):
        dict = {
            'debug': logging.DEBUG,
            'info': logging.INFO,
            'warning': logging.WARNING,
            'error': logging.ERROR,
            'ctirical': logging.CRITICAL
        }
        return dict.get(level)

    def debug(self, msg):
        self.logger.debug(msg)

    def info(self, msg):
        self.logger.info(msg)

    def warning(self, msg):
        self.logger.warning(msg)

    def error(self, msg):
        self.logger.error(msg)

    def critical(self, msg):
        self.logger.critical(msg)
// An highlighted block
if __name__ == '__main__':
    log1 = MyLogging('test',timeInName=True,con_level='debug')
    log1.debug('this is debug')
    log1.logger.info('this is info')
    log1.logger.warning('this is warning')
    log1.logger.error('This is error')
上一篇:超好用的Python 日志记录模块:logging


下一篇:Android图表库MPAndroidChart(一)——了解他的本质,方能得心应手