使用Python中的FileHandler多次打印日志

时间:2017-09-28 13:25:06

标签: python logging robotframework robotframework-ide

执行从Robot Framework执行,其中Test.py已作为库导入,testLog()正在执行,而Logger.py又导入LogMessage()并调用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.")

Test.py

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

Logger.py

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

Log_details.log

RIDE中的消息日志部分在执行期间仅记录每行一次,但名为from django.db import models from apps.area.models import Area from apps.company_dependence.models import CompanyDependence from apps.position.models import Position class People(models.Model): documentPeople = models.AutoField(primary_key=True, null=False) fullname = models.CharField(max_length=50) phone = models.IntegerField() address = models.CharField(max_length=50) email = models.CharField(max_length=50) codeArea = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE) codePosition = models.ForeignKey(Position, null=True, blank=True, on_delete=models.CASCADE) codeCompaDepen = models.ForeignKey(CompanyDependence, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return '{}'.format(self.fullname)的文件多次打印,即第一行记录一次,而第二行记录两次,依此类推。

1 个答案:

答案 0 :(得分:1)

您获得1x消息1,2x消息2和3x消息3。 这是因为您在LogMessage函数中执行日志记录设置,并在每次登录消息时添加文件日志处理程序...所以在第一次运行后,您有1个处理程序,记录您的消息一次,在第二次通话后,您有2个处理程序,可以将您的消息记录两次,等等......

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

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

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