appium或者selenium自动化测试中,经常需要添加一些测试过程中的日志,太复杂的讲太多小白也看不懂,就整个捷径吧。首先,导入logging,并定义内容:
class Logger:
def __init__(self):
self.logname = os.path.join(LOG_PATH, "{}.log".format(time.strftime("%Y%m%d")))
self.logger = logging.getLogger("log")
self.logger.setLevel(logging.INFO)
self.formater = logging.Formatter(
'[%(asctime)s][%(filename)s %(lineno)d][%(levelname)s]: %(message)s')
self.filelogger = logging.FileHandler(self.logname, mode='a', encoding="UTF-8")
self.console = logging.StreamHandler()
self.console.setLevel(logging.DEBUG)
self.filelogger.setLevel(logging.DEBUG)
self.filelogger.setFormatter(self.formater)
self.console.setFormatter(self.formater)
self.logger.addHandler(self.filelogger)
self.logger.addHandler(self.console)
LogRoot = Logger().logger
如果是pytest框架的话,还需要新建pytest.ini文件,添加以下内容
[pytest]
addopts = --capture=no
log_cli = 1
log_cli_level = INFO
最后在需要添加日志的地方添加,例如在查找元素时候,添加
#by是定位方式。locator是元素
LogRoot.info(f'find:by={by},locator={locator}')
或者在未找到元素分支添加
LogRoot.error("未找到元素")
在执行测试用例时候就会实时打印执行日志。
在最开始指定的文件内也可查看。