【问题标题】:Logs getting printed multiple time using FileHandler in Python在 Python 中使用 FileHandler 多次打印日志
【发布时间】:2017-09-29 00:34:14
【问题描述】:

执行从 Robot Framework 中进行,其中 Test.py 已作为库导入,testLog() 正在执行,然后导入 Logger.py 并调用 LogMessage()

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.")

记录器.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.  

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

【问题讨论】:

    标签: python logging robotframework robotframework-ide


    【解决方案1】:

    您会收到 1x 消息 1、2x 消息 2 和 3x 消息 3。 那是因为您将日志记录设置作为LogMessage 函数的一部分执行,并且每次记录消息时都会在其中添加一个文件日志处理程序......所以在第一次运行后,您有一个处理程序记录您的消息一次,第二次之后打电话给你有 2 个处理程序记录你的消息两次,依此类推......

    为了避免这种情况,您只需配置一次记录器。 只需将您的日志配置移动到您将在启动脚本时调用一次的函数中,然后您就可以使用:

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

    当您想登录应用程序中的任何其他文件时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 2020-09-21
      • 2021-02-12
      • 1970-01-01
      • 2017-11-05
      相关资源
      最近更新 更多