Python记录复制

Python记录复制

问题描述:

我有四个文件,Python记录复制

  • Main.py
  • A.py
  • B.py
  • Log_System

我使用的主要使用功能A.py和B.py,所以现在我必须记录所有的信息,当我打电话给他们时。

,所以我写了一个名为log_system创建为每个脚本文件如A.py日志处理程序脚本,B.py

import logging 

def fetchLogger(name="None") : 
    logger = logging.getLogger(__name__) 
    logger.setLevel(logging.DEBUG) 

    if (name == "None"): 
     #create File for Log 
     handler = logging.FileHandler('./engine_log/Generic.log') 
     handler.setLevel(logging.DEBUG) 
     #log format 
     formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 
     handler.setFormatter(formatter) 

     #adding the handler to Logging System 
     logger.addHandler(handler) 
    else: 
     #create File for Log 
     handler = logging.FileHandler('./engine_log/'+str(name)) 
     handler.setLevel(logging.DEBUG) 
     #log format 
     formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 
     handler.setFormatter(formatter) 
     #adding the handler to Logging System 
     logger.addHandler(handler) 
    return logger 

所以,如果我想在脚本文件使用记录A.py,我会写这些线:

import log_system 
"""Log System Building """ 
file_name = 'A.py' 
logger = log_system.fetchLogger(file_name) 

def hello(): 
    try: 
     logger.info("excuting Hello") 
    except: 
     logger.debug("something went wrong in hello") 

但我的日志文件

2017-10-18 14:59:28,695 - log_system - INFO - A.py-excuting Hello 
2017-10-18 14:59:28,695 - log_system - INFO - A.py-excuting Hello 
2017-10-18 14:59:28,695 - log_system - INFO - A.py-excuting Hello 
2017-10-18 14:59:28,695 - log_system - INFO - A.py-excuting Hello 
2017-10-18 14:59:28,695 - log_system - INFO - A.py-excuting Hello 

它是代表多次吃日志.... 所以我应该怎么做?

解决方案

logger = logging.getLogger(name) 

    if logger.hasHandlers(): 
     logger.handlers = [] 

    logger.setLevel(logging.DEBUG) 

    #create File for Log 
    handler = logging.FileHandler('./engine_log/'+str(name)) 
    handler.setLevel(logging.DEBUG) 
    #log format 
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 
    handler.setFormatter(formatter) 
    #adding the handler to Logging System 
    logger.addHandler(handler) 

    return logger 

这是我改变了我的log_system代码,所以我只是清空处理程序列表,如果我创造了一个日志处理器已经使得它不会产生重复的记录。

每次调用fetch_logger时,都会向记录器添加新的FileHandler。每个FileHandler写入日志文件,导致文件中的重复输出。

一种解决方案是调用记录器的hasHandlers方法。如果在记录器上配置了任何处理程序,则这将返回True,然后您可以删除它们。

def fetchLogger(name="None") : 
    logger = logging.getLogger(__name__) 
    if logger.hasHandlers(): 
     # Logger is already configured, remove all handlers 
     logger.handlers = [] 
    # Configure the logger as before. 
    ... 
+0

此解决方案很有用,谢谢。 –