1
我有四個文件,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代碼,所以我只是清空處理程序列表,如果我創造了一個日誌處理器已經使得它不會產生重複的記錄。
此解決方案很有用,謝謝。 –