import logging
from homework.exam_homework_0413.common import contants
from homework.exam_homework_0413.common.read_config import config
def get_logger(name):
logger=logging.getLogger(name)
logger.setLevel(config.get_strValue("log","logger_level"))
fmt="%(asctime)s - %(name)s - %(levelname)s - %(message)s - [%(filename)s:%(lineno)d]"
formatter=logging.Formatter(fmt=fmt)
console_handler=logging.StreamHandler()
console_handler.setLevel(config.get_strValue("log","console_level"))
console_handler.setFormatter(formatter)
file_handler=logging.FileHandler(contants.log_dir+"/case.log",encoding='utf-8')
file_handler.setLevel(config.get_strValue("log","file_level"))
file_handler.setFormatter(formatter)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
return logger
问题:
日志封装成类/函数(如上面logger.py模块,将日志封装成get_logger()函数),使用下面方式调用get_logger()函数,会出现重复写日志问题,如第一条打印一遍,第二条打印2遍 第3条打印3遍...
if __name__=='__main__':
get_logger(__name__).debug("这是bug")
get_logger(__name__).info("这是info")
get_logger(__name__).warning("这是warning")
结果:
2019-04-29 15:57:09,491 - __main__ - DEBUG - 这是bug - [logger.py:33]
2019-04-29 15:57:09,491 - __main__ - INFO - 这是info - [logger.py:34]
2019-04-29 15:57:09,491 - __main__ - INFO - 这是info - [logger.py:34]
2019-04-29 15:57:09,492 - __main__ - WARNING - 这是warning - [logger.py:35]
2019-04-29 15:57:09,492 - __main__ - WARNING - 这是warning - [logger.py:35]
2019-04-29 15:57:09,492 - __main__ - WARNING - 这是warning - [logger.py:35]
解决方法:
每条日志使用同一个对象/函数调用
if __name__=='__main__':
logger=get_logger(__name__)
logger.debug("这是bug")
logger.info("这是info")
logger.warning("这是warning")
结果:
2019-04-29 16:03:24,655 - __main__ - DEBUG - 这是bug - [logger.py:34]
2019-04-29 16:03:24,655 - __main__ - INFO - 这是info - [logger.py:35]
2019-04-29 16:03:24,655 - __main__ - WARNING - 这是warning - [logger.py:36]
|