python-----logging模块初始化及初始化后引用出现的问题解决方法

logging模块初始化

对logging模块进行初始化参数

def get_logger():
    modelPath = os.path.dirname(__file__)
    logger = logging.getLogger(__name__)
    logger.setLevel(10)
    handler = logging.FileHandler(os.path.join(modelPath, '../log/log.txt'),encoding='GBK')
    formatter = logging.Formatter('%(asctime)s - [%(filename)s  -->line:%(lineno)d] - %(levelname)s: %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger

躺坑记录:

·将get_logger引入另一个py文件后,出现了重复多行写入日志的问题

同时插入了多行重复日志,这里是因为第一次调用get_logger()的时候,已经新建了一个handler,所以再次调用就会继续新建,解决方法是,判断当handler存在时,不新建,代码如下:

def get_logger():
    modelPath = os.path.dirname(__file__)
    logger = logging.getLogger(__name__)
    logger.setLevel(10)
    if not logger.handlers:
        handler = logging.FileHandler(os.path.join(modelPath, '../log/log.txt'),encoding='GBK')
        formatter = logging.Formatter('%(asctime)s - [%(filename)s  -->line:%(lineno)d] - %(levelname)s: %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
    return logger

 

你可能感兴趣的:(小白之路,python)