【问题标题】:PyTest - Logfile Replaced if Filename Mentioned in pytest.iniPyTest - 如果 pytest.ini 中提到文件名,则替换日志文件
【发布时间】:2021-03-19 07:35:09
【问题描述】:

我正在编写一组包含许多测试功能的测试文件。我必须为每次运行生成日志文件。所以我在pytest.ini 中添加了下面给出的行:

[pytest]
log_file = Logs/log_file.txt
log_file_level = INFO
log_file_format = %(asctime)s %(levelname)s %(message)s
log_file_date_format = %Y-%m-%d %H:%M:%S

我希望在每次测试运行期间都有每个日志文件。但是该文件在每次运行期间都会用新的log_file.txt 替换旧的。是否有在每次运行期间创建以日期和时间为文件名的新日志文件?

【问题讨论】:

    标签: python logging pytest logfile python-logging


    【解决方案1】:

    使用 datetime 模块中的datetime.strftime() 函数生成文件名。

    from datetime import datetime
    datetime.now().strftime('logfile_%YYYY-%MM-%DDT%HH:%mm:ss.txt')
    

    该命令生成一个以logfile 为前缀的字符串,后跟日期时间,然后是文件格式。 这可用于为每次运行生成单独的文件

    【讨论】:

    • 感谢您的回复。但我想将它添加到pytest.ini 文件中。它是 pytest 的配置文件。我们无法在该文件中导入 python 包。简单的 python 代码不能直接在 pytest.ini 文件中工作。
    • 如果对您有帮助,请参考以上内容。
    • 谢谢。这真的很有帮助。我会发布它。
    【解决方案2】:

    根据@nithin11的回答和他提供的previous answer,我修改了我的conftest.py如下:

    def pytest_configure(config):
        """ Create a log file if log_file is not mentioned in *.ini file"""
        if not config.option.log_file:
            timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d_%H-%M-%S')
            config.option.log_file = 'Logs/log.' + timestamp + ".log"
    

    我还从pytest.ini 中删除了log_file = Logs/log_file.txt。我的新pytest.ini 如下:

    [pytest]
    log_file_level = INFO
    log_file_format = %(asctime)s %(levelname)s %(message)s
    log_file_date_format = %Y-%m-%d %H:%M:%S
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多