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

环境: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()


每运行一次,文件中的error、info就会多一次,调用release()也没有用。在网上查资料,找到原因

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

你可能感兴趣的:(python)