python logging 模块 程序结束后并没有终止进程

在Windows环境下,使用Python 3.5和Spyder,发现logging模块创建的log在程序结束后仍存在,导致下次运行时重复输出。logging模块的全局静态logger对象在解释器会话期间持久存在,每次运行都会添加新的stream handler但不会移除旧的。解决方案是在添加handler前检查已有handler的数量,避免重复添加。

环境:win7 + py3.5 + spyder

调用python logging模块定义一个自己的log类,发现在程序结束后,创建的log还会存在,下次运行时会输出两遍。程序如下:

import os, logging

class MyLogger(object): 
    def __init__(self, name, path='log'):
        log_path = str(os.getcwd()) + '\\' + str(name) + '_' + str(path) + '\\'
        self.error_lg = logging.getLogger('error')
        self.info_lg = logging.getLogger('info')
        if (not os.path.exists(log_path)):
            os.makedirs(log_path)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        if (len(self.error_lg.handlers) == 0):  #确保只有1个handler
            error_h = logging.FileHandler(log_path + 'error.log')   
            error_h.setFormatter(formatter)      
            self.error_lg.addHandler(error_h)
        if (len(self.info_lg.handlers) == 0):
            info_h = logging.FileHandler(log_path + 'info.log')
            info_h.setFormatter(formatter)
            self.info_lg.addHandler(info_h)
    def info(self, msg):
        self.info_lg.info(msg)
    def error(self, msg):
        self.error_lg.error(msg)
    def release(self):
        logging.shutdown()    # flushing and closing any handlers (not removing them)
        
      

if __name__ == '__main__':
    t_log = MyLogger(name='test')
    t_log.error('error-5')
    t_log.info('info-5')
    t_log.release()


<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">每运行一次,文件中的error、info就会多一次,调用release()也没有用。在网上查资料,找到原因</span>

The logging module uses a globally static logger object that persists across your session when you are in the interpreter. So every time you call add_handler you're adding a brand new stream handler but not removing the old one. Logging just iterates through its handlers and sends the output to each, so you have a new copy of the same thing going to the console every time you run.

其中说到:“logging.shutdown(), it is just for flushing and closing any handlers (not removing them).”根据自己的测试情况,在程序结束后,logging仍然会存在,除非 restart python kernel,这样可能会导致内存溢出。

解决办法就是,在每次给logging添加handler之前,判断handlers的数目:

if (len(self.info_lg.handlers) == 0):

另外一个也遇到同样的问题,不过貌似没有提出更好的解决方法:http://stackoverflow.com/questions/24816456/python-logging-wont-shutdown

评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值