Python logging日志模块在使用时会进行重复打印,是否代码不对?还是?
贴上代码:
logme.py:
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
__author__ = 'neilsun'
import logging
import time
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from monitorstack import settings
logger = logging.getLogger('monitorstack')
time_obj = time.gmtime()
log_time = "{year}_{month}_{day}".format(year=time_obj.tm_year,month=time_obj.tm_mon,day=time_obj.tm_mday)
def debug(msg):
logger.setLevel(logging.DEBUG)
debuglogger = logging.StreamHandler()
debuglogger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
debuglogger.setFormatter(formatter)
logger.addHandler(debuglogger)
if settings.DEBUG == True:
logger.debug(msg)
else:
pass
def warning(msg):
logger.setLevel(logging.WARNING)
warnlogger = logging.FileHandler("logs/monitorstack_%s.log" % log_time)
warnlogger.setLevel(logging.WARNING)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
warnlogger.setFormatter(formatter)
logger.addHandler(warnlogger)
logger.warning(msg)
def error(msg):
logger.setLevel(logging.ERROR)
errorlogger = logging.FileHandler("logs/monitorstack_error_%s.log" % log_time)
errorlogger.setLevel(logging.ERROR)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
errorlogger.setFormatter(formatter)
logger.addHandler(errorlogger)
logger.error(msg)
test_log.py:
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
__author__ = 'neilsun'
import logme,time
logme.debug('a')
logme.debug('b')
logme.debug('c')
结果:
2016-09-21 14:59:20,983 - DEBUG - a
2016-09-21 14:59:20,983 - DEBUG - b
2016-09-21 14:59:20,983 - DEBUG - b
2016-09-21 14:59:20,983 - DEBUG - c
2016-09-21 14:59:20,983 - DEBUG - c
2016-09-21 14:59:20,983 - DEBUG - c
求解
logger的handler只需要Add一次。
你在Logme.py中每次调用debug都会设置添加一个log handler,每个handler都会打印一次log,所有就会出现调用几次debug,就会打印几条相同的log。
你包装的logme模块的功能, logging模块都已经有了, 建议看看Logging HOWTO会让你事半功倍的.