框架增加log模块

  • 记录程序运行信息
  • 方便定位问题

控制台

import logging
logger = logging.getLogger('7an')
logger.error('error')
ERROR:7an:error

python日志模块logging

  • DEBUG
  • INFO
  • WARNING
  • ERROR

log

log_util.py

import logging
import os
import time

from utils.get_filepath import get_log_path

log_path = get_log_path()

if not os.path.exists(log_path):
    os.mkdir(log_path)


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.DEBUG)
        # 创建日志输入的格式
        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.filelogger.setLevel(logging.DEBUG)
        # 文件存放日志格式
        self.filelogger.setFormatter(self.formater) 
        # 创建日志处理器,在控制台打印
        self.console = logging.StreamHandler()
        # 设置控制台打印日志界别
        self.console.setLevel(logging.DEBUG)
        # 控制台打印日志格式
        self.console.setFormatter(self.formater)
        # 将日志输出渠道添加到日志收集器中
        self.logger.addHandler(self.filelogger)
        self.logger.addHandler(self.console)


logger = Logger().logger

if __name__ == '__main__':
    logger.debug("我打印DEBUG日志")
    logger.info("我打印INFO日志")
    logger.warning("我打印WARNING日志")
    logger.error("我打印ERROR日志")

使用log

logger.info("查找元素并输入内容")
logger.info("点击按钮")

断言封装

assert_util.py

from utils.log_util import logger
def assert_compare(expect, compare, actual):
    """
    :param expect: 预期结果
    :param compare: 断言方式
    :param actual:实际结果
    :return:
    """
    logger.info(f"预期结果:{expect}{compare}{actual}")
    try:
        if compare == "==":
            assert expect == actual
        elif compare == "!=":
            assert expect != actual
        elif compare == ">":
            assert expect > actual
        elif compare == "<":
            assert expect < actual
        elif compare == "in":
            assert expect in actual
        elif compare == "not in":
            assert expect not in actual
        elif compare == ">=":
            assert expect >= actual
        elif compare == "<=":
            assert expect <= actual
        elif compare == "is":
            assert expect is actual
        elif compare == "is not":
            assert expect is not actual
        else:
            try:
                raise NameError(f"{compare}断言方式错误,请正确填写")
            except Exception as e:
                logger.error(e)
                raise
        logger.info("断言成功")
    except AssertionError as e:
        logger.error(f"断言失败{e}")

断言log

assert_compare(title, "==", "百度一下,你就知道")
作者设置了回复可见