BDD - Python Behave log 为每个 Scenario 生成对应的 log 文件

BDD - Python Behave log 为每个 Scenario 生成对应的 log 文件

  • 引言
  • 应用 Behave 官网 Log 配置文件
    • 项目 Setup
      • Feature 文件
      • steps 文件
      • Log 配置文件
      • environment.py 文件
      • behave.ini
    • 执行结果
  • 直接应用 Python logging 模块
    • 方式 1:应用 log 配置文件
      • log 配置文件
      • environment.py
      • Steps 文件
      • 执行结果
    • 方式 2:logging 方法配置
      • environment.py
      • 执行结果
    • 方式 3:dictConfig 配置
      • environment.py
      • 执行结果
  • 总结

引言

文章《BDD - Python Behave log 日志》只是简单的介绍了一下 log 的基本配置,而且默认是输出到 Console,这对于日常自动化测试是不够全面的,不利于 Automation Triage。今天就来了解一下更友好的日志配制,为每个 Scenario 配置不同的 log 文件,极大地方便定位 Scenario 运行失败的原因。

想了解更多 Behave 相关的文章,欢迎阅读《Python BDD Behave 系列》,持续更新中。

应用 Behave 官网 Log 配置文件

首先应用一下 Behave 官网 Log with Configfile 例子,发现所有的日志都会输出到一个固定的文件中。目前 Behave 1.2.6 版本 context.config.setup_logging() 方法还不支持动态改变 config 文件中的参数值,但是可以通过改源码来实现,可参考 Add support for value substitution in logging config file

项目 Setup

Feature 文件

log_with_config_file.feature, 3 个 Scenarios

# BDD/Features/log/log_with_config_file.featureFeature: Logging Example@log_testScenario: First ScenarioGiven I have a scenario 1When I perform an actionThen I should see the result@log_testScenario Outline: Second ScenarioGiven I have a scenario <number>When I perform an actionThen I should see the resultExamples:|number||2||3|

steps 文件

简单的日志记录

# BDD/steps/log_with_config_file_steps.pyfrom behave import given, when, then
import logging
from behave.configuration import LogLevel@given("I have a scenario {number}")
def step_given_scenario(context, number):logging.info(f"This is a log from scenario {number}")@when("I perform an action")
def step_when_perform_action(context)logging.info("I perform an action")@then("I should see the result")
def step_then_see_result(context):logging.error("I did not see the result")

Log 配置文件

behave_logging.ini
配置了文件输出,也可以配置日志输出到文件和 Console,这里日志文件是固定的 BDD/logs/behave.log

 # BDD/config/behave_logging.ini[loggers]keys=root[handlers]keys=Console,File[formatters]keys=Brief[logger_root]level = DEBUG# handlers = Filehandlers = Console,File[handler_File]class=FileHandlerargs=("BDD/logs/behave.log", 'w')level=DEBUGformatter=Brief[handler_Console]class=StreamHandlerargs=(sys.stderr,)level=DEBUGformatter=Brief[formatter_Brief]format= LOG.%(levelname)-8s  %(name)-10s: %(message)sdatefmt=

environment.py 文件

通过调用 Behave 方法 context.config.setup_logging() 应用上面的 log 配置文件,

# BDD/environment.pydef before_all(context):# create log diros.makedirs("BDD/logs", exist_ok=True) context.config.setup_logging(configfile="BDD/config/behave_logging.ini")

behave.ini

Behave 默认 log_capture 是 true 的,运行成功的 Scenario 是不会输出日志的。所以将该值设置为 false,确保不管 Scenario 运行成功与否,都输出日志。stdout_capture 为 false 是允许输出 print 语句,为 true 则不会输出。

# behave.ini
[behave]
paths=BDD/Features/log/log_with_config_file.feature
tags = log_test
log_capture = false
stdout_capture = false

执行结果

因为 behave.ini 已经配置了 feature 文件 path 及 tags,所以只需在项目根目录下直接运行 behave 命令就可以了。

日志按配置格式输出到 Console,同时也输出到 behave.log 文件中。

PS C:\Automation\Test> behave
Feature: Logging Example # BDD/Features/log/log_with_config_file.feature:2@log_testScenario: First Scenario       # BDD/Features/log/log_with_config_file.feature:5Given I have a scenario 1    # BDD/steps/log_with_config_file_steps.py:7      
LOG.INFO      root      : This is a log from scenario 1When I perform an action     # BDD/steps/log_with_config_file_steps.py:14     
LOG.INFO      root      : I perform an actionThen I should see the result # BDD/steps/log_with_config_file_steps.py:22     
LOG.ERROR     root      : I did not see the result
scenario_name Second_Scenario_--_@1.1_@log_testScenario Outline: Second Scenario -- @1.1   # BDD/Features/log/log_with_config_file.feature:18Given I have a scenario 2                 # BDD/steps/log_with_config_file_steps.py:7
LOG.INFO      root      : This is a log from scenario 2When I perform an action                  # BDD/steps/log_with_config_file_steps.py:14
LOG.INFO      root      : I perform an actionThen I should see the result              # BDD/steps/log_with_config_file_steps.py:22
LOG.ERROR     root      : I did not see the result
scenario_name Second_Scenario_--_@1.2_@log_testScenario Outline: Second Scenario -- @1.2   # BDD/Features/log/log_with_config_file.feature:19Given I have a scenario 3                 # BDD/steps/log_with_config_file_steps.py:7
LOG.INFO      root      : This is a log from scenario 3When I perform an action                  # BDD/steps/log_with_config_file_steps.py:14
LOG.INFO      root      : I perform an actionThen I should see the result              # BDD/steps/log_with_config_file_steps.py:22
LOG.ERROR     root      : I did not see the result1 feature passed, 0 failed, 0 skipped
3 scenarios passed, 0 failed, 0 skipped
9 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.010s

在这里插入图片描述

直接应用 Python logging 模块

针对不同的 Scenario 动态创建 log 文件,输出到对应的 log 文件中,这里有三种方式实现

方式 1:应用 log 配置文件

log 配置文件

注意 args=(‘%(logfilename)s’,‘w’) 文件名可通过参数来设置的,不再是固定的。

# BDD/config/logging.ini
[loggers]
keys=root[handlers]
keys=consoleHandler,fileHandler[formatters]
keys=sampleFormatter[logger_root]
level=DEBUG
handlers=consoleHandler,fileHandler[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=sampleFormatter
args=(sys.stdout,)[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=sampleFormatter
args=('%(logfilename)s','w')[formatter_sampleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S[log_file_template]
path={scenario_name}_{timestamp}.log

environment.py

根据 feature 名 和 Scenario 名及其位置生成 log 文件名

logging.config.fileConfig(“BDD/config/logging.ini”, defaults={‘logfilename’: log_file}) 应用 log 配置文件和动态设置 log 输出文件名
context.logger = logging.getLogger(f"{feature_name_str}_@{scenario_location_line}") 保持 log 的上下文关系

# BDD/environment.pydef before_scenario(context, scenario):# create log dirfeature_name_str = context.feature.name.replace(" ", "_")log_dir = f"BDD/logs/{feature_name_str}"os.makedirs(log_dir, exist_ok=True) # generate log file pathscenario_name = scenario.name.replace(" ", "_")current_time = datetime.datetime.now()formatted_time = current_time.strftime("%Y-%m-%d-%H-%M-%S")scenario_location_line = scenario.location.linelog_file = os.path.join(log_dir, f"{scenario_name}_{scenario_location_line}_{formatted_time}.log")# log setuplogging.config.fileConfig("BDD/config/logging.ini", defaults={'logfilename': log_file})context.logger = logging.getLogger(f"{feature_name_str}_@{scenario_location_line}")

Steps 文件

context.logger 拿到 logger 对象

# BDD/steps/log_with_config_file_steps.pyfrom behave import given, when, then
import logging
from behave.configuration import LogLevel@given("I have a scenario {number}")
def step_given_scenario(context, number):context.logger.info(f"This is a log from scenario {number}")@when("I perform an action")
def step_when_perform_action(context):context.logger.error(f"I perform an action")@then("I should see the result")
def step_then_see_result(context):context.logger.error("I should see the result")

执行结果

behave.ini 文件中的配置还跟之前一样,在项目根目录下直接运行 behave 命令即可。

log 有输出到终端:

PS C:Automation\Test> behave    
Feature: Logging Example # BDD/Features/log/log_with_config_file.feature:2@log_testScenario: First Scenario       # BDD/Features/log/log_with_config_file.feature:5Given I have a scenario 1    # BDD/steps/log_with_config_file_steps.py:7      
2024-03-09 16:00:09 - Logging_Example_@5 - INFO - This is a log from scenario 1   When I perform an action     # BDD/steps/log_with_config_file_steps.py:14     
2024-03-09 16:00:09 - Logging_Example_@5 - ERROR - I perform an actionThen I should see the result # BDD/steps/log_with_config_file_steps.py:22
2024-03-09 16:00:10 - Logging_Example_@5 - ERROR - I should see the result@log_testScenario Outline: Second Scenario -- @1.1   # BDD/Features/log/log_with_config_file.feature:18Given I have a scenario 2                 # BDD/steps/log_with_config_file_steps.py:7
2024-03-09 16:00:10 - Logging_Example_@18 - INFO - This is a log from scenario 2When I perform an action                  # BDD/steps/log_with_config_file_steps.py:14
2024-03-09 16:00:10 - Logging_Example_@18 - ERROR - I perform an actionThen I should see the result              # BDD/steps/log_with_config_file_steps.py:22
2024-03-09 16:00:10 - Logging_Example_@18 - ERROR - I should see the result@log_testScenario Outline: Second Scenario -- @1.2   # BDD/Features/log/log_with_config_file.feature:19Given I have a scenario 3                 # BDD/steps/log_with_config_file_steps.py:7
2024-03-09 16:00:10 - Logging_Example_@19 - INFO - This is a log from scenario 3When I perform an action                  # BDD/steps/log_with_config_file_steps.py:14
2024-03-09 16:00:10 - Logging_Example_@19 - ERROR - I perform an actionThen I should see the result              # BDD/steps/log_with_config_file_steps.py:22
2024-03-09 16:00:10 - Logging_Example_@19 - ERROR - I should see the result1 feature passed, 0 failed, 0 skipped
3 scenarios passed, 0 failed, 0 skipped
9 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.015s    

同时,feature 名的 log 目录已经创建,并每个 Scenario 都有对应的 log 文件

在这里插入图片描述

在这里插入图片描述

方式 2:logging 方法配置

在 environment.py 文件中,通过 logging 模块方法配置 log 属性, 其它文件跟方式 1 保持不变

environment.py

# BDD/environment.pydef scenario_log_setup(scenario, log_file):# set loggerlogger = logging.getLogger(scenario.name)logger.setLevel(logging.DEBUG)# add handler for loggerfile_handler = logging.FileHandler(log_file)file_handler.setLevel(logging.DEBUG)console_handler = logging.StreamHandler()console_handler.setLevel(logging.DEBUG)# set format for loggerlog_format = '%(asctime)s %(levelname)s : %(message)s'formatter = logging.Formatter(log_format)file_handler.setFormatter(formatter)console_handler.setFormatter(formatter)logger.addHandler(file_handler)logger.addHandler(console_handler)return loggerdef before_scenario(context, scenario):# create log dirfeature_name_str = context.feature.name.replace(" ", "_")log_dir = f"BDD/logs/{feature_name_str}"os.makedirs(log_dir, exist_ok=True) # generate log file pathscenario_name = scenario.name.replace(" ", "_")  current_time = datetime.datetime.now()formatted_time = current_time.strftime("%Y-%m-%d-%H-%M-%S")scenario_location_line = scenario.location.linelog_file = os.path.join(log_dir, f"{scenario_name}_{scenario_location_line}_{formatted_time}.log")# log setupcontext.logger = scenario_log_setup(scenario, log_file)

执行结果

终端输出并写入 log 文件中

PS C:\Automation\Test> behave
Feature: Logging Example # BDD/Features/log/log_with_config_file.feature:2        @log_testScenario: First Scenario       # BDD/Features/log/log_with_config_file.feature:5Given I have a scenario 1    # BDD/steps/log_with_config_file_steps.py:7      
2024-03-09 16:42:02,505 CRITICAL : This is a log from scenario 1When I perform an action     # BDD/steps/log_with_config_file_steps.py:14     
2024-03-09 16:42:02,505 ERROR : I perform an actionThen I should see the result # BDD/steps/log_with_config_file_steps.py:22     
2024-03-09 16:42:02,505 ERROR : I should see the result@log_testScenario Outline: Second Scenario -- @1.1   # BDD/Features/log/log_with_config_file.feature:18Given I have a scenario 2                 # BDD/steps/log_with_config_file_steps.py:7       
2024-03-09 16:42:02,533 CRITICAL : This is a log from scenario 2When I perform an action                  # BDD/steps/log_with_config_file_steps.py:14
2024-03-09 16:42:02,534 ERROR : I perform an actionThen I should see the result              # BDD/steps/log_with_config_file_steps.py:22
2024-03-09 16:42:02,534 ERROR : I should see the result@log_testScenario Outline: Second Scenario -- @1.2   # BDD/Features/log/log_with_config_file.feature:19Given I have a scenario 3                 # BDD/steps/log_with_config_file_steps.py:7
2024-03-09 16:42:02,541 CRITICAL : This is a log from scenario 3When I perform an action                  # BDD/steps/log_with_config_file_steps.py:14
2024-03-09 16:42:02,543 ERROR : I perform an actionThen I should see the result              # BDD/steps/log_with_config_file_steps.py:22
2024-03-09 16:42:02,545 ERROR : I should see the result1 feature passed, 0 failed, 0 skipped
3 scenarios passed, 0 failed, 0 skipped
9 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.018s

log 文件生成

在这里插入图片描述

在这里插入图片描述

方式 3:dictConfig 配置

在 environment.py 文件中,通过定义一个 Log Config dict 调用 logging.config.dictConfig 配置 log 属性, 其它文件跟方式 1 保持不变

environment.py

def scenario_log_setup_with_config_dict(scenario, log_file):logging_config = {'version': 1,'disable_existing_loggers': False,'formatters': {'standard': {'format': '%(asctime)s %(levelname)s : %(message)s'},},'handlers': {'file_handler': {'class': 'logging.FileHandler','filename': log_file,'formatter': 'standard',},'console_handler':{'class':'logging.StreamHandler','formatter': 'standard',}},'loggers': {'': {'handlers': ['file_handler','console_handler'],'level': 'DEBUG',},}}logging.config.dictConfig(logging_config)return logging.getLogger(scenario.name)def before_scenario(context, scenario):# create log dirfeature_name_str = context.feature.name.replace(" ", "_")log_dir = f"BDD/logs/{feature_name_str}"os.makedirs(log_dir, exist_ok=True) scenario_name = scenario.name.replace(" ", "_")# generate log file pathcurrent_time = datetime.datetime.now()formatted_time = current_time.strftime("%Y-%m-%d-%H-%M-%S")scenario_location_line = scenario.location.linelog_file = os.path.join(log_dir, f"{scenario_name}_{scenario_location_line}_{formatted_time}.log")# log setup# good 1# logging.config.fileConfig("BDD/config/logging.ini", defaults={'logfilename': log_file})# context.logger = logging.getLogger(f"{feature_name_str}_@{scenario_location_line}")# good 2# context.logger = scenario_log_setup(scenario, log_file)# good 3context.logger = scenario_log_setup_with_config_dict(scenario, log_file)

执行结果

终端输出并写入 log 文件中

PS C:\Automation\Test> behave
Feature: Logging Example # BDD/Features/log/log_with_config_file.feature:2@log_testScenario: First Scenario       # BDD/Features/log/log_with_config_file.feature:5Given I have a scenario 1    # BDD/steps/log_with_config_file_steps.py:7
2024-03-09 17:17:31,197 CRITICAL : This is a log from scenario 1When I perform an action     # BDD/steps/log_with_config_file_steps.py:14
2024-03-09 17:17:31,199 ERROR : I perform an actionThen I should see the result # BDD/steps/log_with_config_file_steps.py:22
2024-03-09 17:17:31,202 ERROR : I should see the result@log_testScenario Outline: Second Scenario -- @1.1   # BDD/Features/log/log_with_config_file.feature:18Given I have a scenario 2                 # BDD/steps/log_with_config_file_steps.py:7
2024-03-09 17:17:31,212 CRITICAL : This is a log from scenario 2When I perform an action                  # BDD/steps/log_with_config_file_steps.py:14
2024-03-09 17:17:31,212 ERROR : I perform an actionThen I should see the result              # BDD/steps/log_with_config_file_steps.py:22
2024-03-09 17:17:31,212 ERROR : I should see the result@log_testScenario Outline: Second Scenario -- @1.2   # BDD/Features/log/log_with_config_file.feature:19Given I have a scenario 3                 # BDD/steps/log_with_config_file_steps.py:7
2024-03-09 17:17:31,212 CRITICAL : This is a log from scenario 3When I perform an action                  # BDD/steps/log_with_config_file_steps.py:14
2024-03-09 17:17:31,212 ERROR : I perform an actionThen I should see the result              # BDD/steps/log_with_config_file_steps.py:22
2024-03-09 17:17:31,212 ERROR : I should see the result1 feature passed, 0 failed, 0 skipped
3 scenarios passed, 0 failed, 0 skipped
9 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.004s

log 文件生成
在这里插入图片描述

在这里插入图片描述

总结

上面介绍了几种 log 处理方式, 比较推荐应用 Python logging 模块采用方式 1,应用 log 配置文件,优点就是代码可读性,可维护性更好。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/525617.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【学习笔记】Vue3源码解析:第二部分-实现响应式(5)

课程地址&#xff1a;【已完结】全网最详细Vue3源码解析&#xff01;&#xff08;一行行带你手写Vue3源码&#xff09; 第二部分-实现响应式&#xff08;5&#xff09;&#xff1a;&#xff08;对应课程的第18-21节&#xff09; 第18节&#xff1a;《创建ref实例》 vue3中 re…

Linux - 基础IO

1、回顾 1.1、来段代码回顾C文件接口 hello.c写文件 #include <stdio.h> #include <string.h> int main() {FILE *fp fopen("myfile", "w");if(!fp){printf("fopen error!\n");}const char *msg "hello world!\n";in…

超好用的一键生成原创文案方法

在现代社会中&#xff0c;原创文案不管是在营销中&#xff0c;还是在品牌推广中都起着至关重要的作用。然而&#xff0c;对于许多人来说&#xff0c;创作出令人印象深刻且引人注目的原创文案并不容易。但随着技术的发展&#xff0c;我们现在可以利用一键生成原创文案的方法来帮…

Googlenet网络架构

原文链接&#xff1a;[1409.4842v1] Going Deeper with Convolutions (arxiv.org) 图源&#xff1a;深入解读GoogLeNet网络结构&#xff08;附代码实现&#xff09;-CSDN博客 表截自原文 以下&#x1f4d2;来自博客深入解读GoogLeNet网络结构&#xff08;附代码实现&#xff0…

PHAMB: 病毒数据分箱

Genome binning of viral entities from bulk metagenomics data | Nature Communications 安装 ### New dependencies *Recommended* conda install -c conda-forge mamba mamba create -n phamb python3.9 conda activate phamb mamba install -c conda-forge -c biocond…

《2024国家自然科学基金青年基金》 相关申请注意事项解读

一 年龄计算 2004 对应 89 2005 对应 90 2006 对应 91 2007 对应 92 2008 对应 93 2009 对应 94 2010 对应 95 .。。 二 资助比例&#xff08;2023&#xff09; 2024年 23.13% 2023年 24% 三 2024年政策变动&#xff0c;只能申请3年的30万&#xff0c;不能像23年一样选择10-20的…

鸿蒙Harmony应用开发—ArkTS声明式开发(通用属性:外描边设置)

设置组件外描边样式。 说明&#xff1a; 从API Version 11开始支持。后续版本如有新增内容&#xff0c;则采用上角标单独标记该内容的起始版本。 outline outline(value: OutlineOptions) 统一外描边样式设置接口。 卡片能力&#xff1a; 从API version 11开始&#xff0c;该…

C++虚继承的一些细节

C虚继承的一些细节 何时使用虚继承普通继承的类对象布局虚继承类对象布局虚函数表指针虚函数表内容 何时使用虚继承 看代码&#xff0c;代码主要是菱形继承&#xff0c;base里面的成员变量会存在二义性 #include<iostream> using namespace std;class base { public:in…

21-Java观察者模式 ( Observer Pattern )

Java备忘录模式 摘要实现范例 观察者模式 ( Observer Pattern ) 常用于对象间存在一对多关系时&#xff0c;比如&#xff0c;当一个对象被修改时&#xff0c;需要自动通知它的依赖对象 观察者模式属于行为型模式 摘要 1. 意图 定义对象间的一种一对多的依赖关系&#xff…

IPsec VPN配置方式

一、手工方式建立 手工方式建立IPsec的场景&#xff0c;全部参数需要手工配置&#xff0c;工作量大&#xff0c;适用于小型静态网络。 当企业总部与分支通过FW1和FW2之间建立的IPsec隧道进行安全通信。 手工配置步骤主要有四个&#xff1a; ①定义需要保护的数据流&#xff1…

蓝桥杯倒计时 36天-DFS练习

文章目录 飞机降落仙境诅咒小怂爱水洼串变换 飞机降落 思路&#xff1a;贪心暴搜。 #include<bits/stdc.h>using namespace std; const int N 10; int t,n; //这题 N 比较小&#xff0c;可以用暴力搜搜复杂度是 TN*N! struct plane{int t,d,l; }p[N]; bool vis[N];//用…

STL空间配置器

参考《STL源码剖析-侯捷》一书 (SGI版本STL) 前置 六大组件 空间配置器实现 SGI版本的空间配置器有两个&#xff0c;一个名为allocator&#xff0c;一个名为alloc。前者符合部分标准&#xff0c;但效率不好&#xff0c;只是对operator new和operator delete进行了封装&#…