2017-09-28 41 views
0

执行发生于Robot Framework,其中Test.py已作为库导入并且testLog()正在执行,后者又导入Logger.py并调用LogMessage()在Python中使用FileHandler多次打印日志

Test.py

import Logger 
def testLog(): 
    Logger.LogMessage("This is the first line of the log file.") 
    Logger.LogMessage("This is the second line of the log file.") 
    Logger.LogMessage("This is the third line of the log file.") 

Logger.py

import logging 
def LogMessage(message): 
    LOG_FILENAME = "C://Log_Details".log" 
    logger = logging.getLogger()  
    logFileHandler = logging.FileHandler(LOG_FILENAME) 
    logger.addHandler(logFileHandler) 

Log_Details.log

This is the first line of the log file. 
This is the second line of the log file. 
This is the second line of the log file. 
This is the third line of the log file. 
This is the third line of the log file. 
This is the third line of the log file. 

在乘坐消息日志部执行期间记录每行只是一次,但名为Log_details.log的文件会多次打印它们,即第一行会记录一次第二次获得记录两次,依此类推。

回答

1

你得到1X消息1,2消息2和3倍的消息3 那是因为你执行你的日志设置为您LogMessage功能的一部分,并在那里你添加在每次登录的消息时文件日志处理..所以在第一次运行后,你有1个处理程序记录你的消息一次,第二次通话后你有2个处理程序记录你的消息两次,等等......

为了避免那只是你想配置你的记录器一次。 只需将日志记录配置,当你开始你的脚本,从此你可以使用你会调用一次函数:

import logging 
log = logging.getLogger(__name__) 
log.info('smth') 

每当你觉得在你的应用程序的任何其他文件记录。