pytest日志配置

pytest默认输出日志如下:

 

为了让日志看起来更加舒服,我们可以在pytest.ini文件中增加如下配置


[pytest]
;日志开关 true false
log_cli = true


;输出到terminal
;日志级别
log_cli_level = info
;打印详细日志,相当于命令行加 -vs
addopts = --capture=no
;日志格式
log_cli_format = %(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)
;日志时间格式
log_cli_date_format = %Y-%m-%d %H:%M:%S


; 输出到文件,log文件需要手动创建
;日志文件位置
log_file = ./log/test.log
;日志文件等级
log_file_level = info
;日志文件格式
log_file_format = %(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)
;日志文件日期格式
log_file_date_format = %Y-%m-%d %H:%M:%S


1 # 可以动态生成log文件的名称,不过需要的pytest版本比较高
2 @pytest.fixture(scope="session", autouse=True)
3 def manage_logs(request):
4     """Set log file name same as test name"""
5     now = time.strftime("%Y-%m-%d %H-%M-%S")
6     log_name = 'output/log/' + now + '.logs'
7 
8     request.config.pluginmanager.get_plugin("logging-plugin") \
9         .set_log_path(return_path(log_name))

 或

def pytest_configure(config):
    time_now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    config.option.log_file = os.path.join(config.rootdir, 'logs', f'{time_now}.log')

 

 注意:如果当前IDE设置的默认编码是UTF-8,那么pytest.ini文件里面不可以加任何注释等与配置无关的信息,否则运行报错

            如果当前IDE设置的默认编码是GBK,那么pytest.ini文件里面可以加注释等信息,运行不会报错

posted @ 2023-11-20 10:35  术科术  阅读(258)  评论(0编辑  收藏  举报