需求
记录程序运行过程中总共log了多少次,各个级别的log各打了多少次
实现
自定义logging的handler,参考自https://stackoverflow.com/questions/812477/how-many-times-was-logging-error-called
import logging
import os
class MsgCounterHandler(logging.Handler):
level2count = None
def __init__(self, *args, **kwargs):
super(MsgCounterHandler, self).__init__(*args, **kwargs)
self.level2count = {}
def emit(self, record):
l = record.levelname
if (l not in self.level2count):
self.level2count[l] = 0
self.level2count[l] += 1
if not os.path.exists(r'd:\log'):
os.mkdir(r'd:\log')
log_path = os.path.join(r'd:\log', 'test')
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename=r'%s.log' % log_path,
filemode='w')
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
logger = logging.getLogger(__name__)
mch = MsgCounterHandler()
logger.addHandler(mch)
logger.warning('232432323')
logger.info('1')
logger.error(2)
print mch.level2count
运行结果
main : WARNING 232432323
main : INFO 1
main : ERROR 2
{‘INFO’: 1, ‘WARNING’: 1, ‘ERROR’: 1}