日志以及日志封装

日志

输出日志信息

import logging

# 调用 指定级别 输入日志信息
logging.debug("this is a debug")
logging.info("this is a info")
logging.warning("this is a warning")
logging.error("this is a error")
logging.critical("this is a critical")

这些为常量  

设置日志级别

import logging

# 设置日志级别 常量
logging.basicConfig(level=logging.DEBUG)

# 调用 指定级别 输入日志信息
logging.debug("this is a debug")
logging.info("this is a info")
logging.warning("this is a warning")
logging.error("this is a error")
logging.critical("this is a critical")

设置日志格式

import logging

fmt = '%(asctime)s %(levelname)s [%(name)s] [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s'
# 不同样式 自己修改
# fmt = '%(asctime)s %(levelname)s [%(name)s] |%(filename)s(%(funcName)s:%(lineno)d)| - %(message)s'
logging.basicConfig(level=logging.INFO,format=fmt)

logging.debug("调试")
logging.info("信息")
logging.warning("警告")
logging.error("错误")

 输入到文件中

import logging

fmt = '%(asctime)s %(levelname)s [%(name)s] [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s'

logging.basicConfig(level=logging.INFO,format=fmt,filename="./log/l1.log")

logging.debug("调试")
logging.info("信息")
logging.warning("警告")
logging.error("错误")

logging应用

info在base

error在test_login业务层

出错抛异常 error 异常打印日志

时间切割:重要

输出到终端中 加处理器

"""
    学习logging底层 模块实现
"""

import logging

# 获取logger
logger = logging.getLogger()

# 获取控制台 处理器
sh = logging.StreamHandler()
# 将处理器添加到logger
logger.addHandler(sh)

# 设置级别
logger.setLevel(logging.INFO)
logging.info("info")
logging.debug("debug")

添加文件处理器 既可以输出到文件中

import logging.handlers
# logging 是包名 导入包名时会自动执行包下面的__init__文件 所以这样导入 相当于导入logging
# handlers是模块名

# 获取logger
logger = logging.getLogger()
# 获取控制台 处理器
sh = logging.StreamHandler()
# 到文件 根据时间切割
fh = logging.handlers.TimedRotatingFileHandler(filename="./log/log_time.log",
                                          when="M",
                                          interval=1,
                                          backupCount=3)
# 将处理器添加到logger
logger.addHandler(sh)
logger.addHandler(fh)
# 设置级别
logger.setLevel(logging.INFO)
logging.info("info")
logging.debug("debug")

加格式器

import logging.handlers
# logging 是包名 导入包名时会自动执行包下面的__init__文件 所以这样导入 相当于导入logging
# handlers是模块名

# 获取logger
logger = logging.getLogger()
# logger = logging.getLogger("admin")
# 获取控制台 处理器
sh = logging.StreamHandler()
# 到文件 根据时间切割
# 一分钟保存一个文件 有三个备份
fh = logging.handlers.TimedRotatingFileHandler(filename="./log/log_time.log",
                                                when="M",
                                                interval=1,
                                                backupCount=3)

fmt = '%(asctime)s %(levelname)s [%(name)s] [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s'
fm = logging.Formatter(fmt)

sh.setFormatter(fm)
fh.setFormatter(fm)
# 将处理器添加到logger
logger.addHandler(sh)
logger.addHandler(fh)
# 设置级别
logger.setLevel(logging.INFO)
logging.info("info")
logging.debug("debug")

1.设置logger同一级别 为所有处理器的最低级别 就算是自己设置的 也要遵循其最低级别

2.设置单个处理器

import logging.handlers
# logging 是包名 导入包名时会自动执行包下面的__init__文件 所以这样导入 相当于导入logging
# handlers是模块名

# 获取logger
logger = logging.getLogger()
# logger = logging.getLogger("admin")
# 获取控制台 处理器
sh = logging.StreamHandler()
# 到文件 根据时间切割
# 一分钟保存一个文件 有三个备份
th = logging.handlers.TimedRotatingFileHandler(filename="./log/log_time.log",
                                                when="M",
                                                interval=1,
                                                backupCount=3)

th.setLevel(logging.ERROR) # 只显示error及其以上
fmt = '%(asctime)s %(levelname)s [%(name)s] [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s'
fm = logging.Formatter(fmt)

sh.setFormatter(fm)
th.setFormatter(fm)
# 将处理器添加到logger
logger.addHandler(sh)
logger.addHandler(th)
# 设置级别
logger.setLevel(logging.INFO)
logging.info("info")
logging.debug("debug")
logging.error("error")
logging.warning("warning")
logger.setLevel(logging.WARNING)
th.setLevel(logging.DEBUG) # 也只会显示WARNING以上级别的

封装logger 这里用了单例 不使用单例封装:会重复

S 1 3 一秒钟保存一个 有三个备份

midnight 1 3 一整夜保存一个 有三个备份

使用单例封装
import logging.handlers

class GetLogger:
    logger = None
    @classmethod
    def get_logger(cls):
        if cls.logger is None:
            cls.logger = logging.getLogger()

            cls.logger.setLevel(logging.INFO)

            sh = logging.StreamHandler()

            th = logging.handlers.TimedRotatingFileHandler(filename="../../log/l4.log",
                                                           when="midnight",
                                                           interval=1,
                                                           backupCount=3,
                                                           encoding="utf-8")

            fmt = '%(asctime)s %(levelname)s [%(name)s] [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s'
            fm = logging.Formatter(fmt)

            sh.setFormatter(fm)
            th.setFormatter(fm)

            cls.logger.addHandler(sh)
            cls.logger.addHandler(th)

        return cls.logger
from selenium.webdriver.support.wait import WebDriverWait
import time
from case_login.base.get_logger import GetLogger


# 使用单例
log = GetLogger().get_logger()


class Base:
    def __init__(self, driver):
        log.info("正在初始化driver{}".format(driver))
        self.driver = driver

    def base_find_element(self, loc, timeout=30, poll=0.5):
        log.info("正在查找元素{}".format(loc))
        return WebDriverWait(self.driver, timeout=timeout, poll_frequency=poll).until(lambda x: x.find_element(*loc))

    def base_click(self, loc):
        log.info("正在点击元素{}".format(loc))
        self.base_find_element(loc).click()

    def base_input(self, loc, value):
        log.info("正在给元素输入内容{}".format(loc))
        el = self.base_find_element(loc)
        # 清空
        log.info("正在给元素{}清空".format(loc))
        el.clear()
        # 输入
        log.info("正在给元素{}输入内容".format(loc))
        el.send_keys(value)

    def base_get_text(self, loc):
        # 注意:一定要返回元素的文本信息
        log.info("正在获取元素{}文本".format(loc))
        return self.base_find_element(loc).text

    # 截图
    def base_get_screen_shot(self):
        self.driver.get_screenshot_as_file("../../image/{}.png".format(time.strftime("%Y_%m_%d %H_%M_%S")))

    # 封装判断元素是否存在
    def base_if_exist(self, loc):
        try:
            self.base_find_element(loc, timeout=2)
            log.info("元素{}存在".format(loc))

            return True
        except:
            log.info("元素{}不存在".format(loc))
            return False
from case_login.tool.get_log import get_logging
from case_login.base.get_logger import GetLogger

log = GetLogger().get_logger()

def get_data():
    arr = []
    for data in read_json("login.json").values():
        arr.append((data.get("username"),
                    data.get("password"),
                    data.get("verify_code"),
                    data.get("expect_result"),
                    data.get("success")))
    return arr  # 注意:必须进行return 返回

# def get_data():
#     arr = []
#     for data in read_txt("login.txt"):
#         arr.append(tuple(data.strip().split(",")))
#     return arr


# 新建测试类
class TestLogin(unittest.TestCase):
    login = None

    @classmethod
    def setUpClass(cls):
        try:
            # 实例化 获取页面对象 PageLogin
            cls.login = PageLogin(GetDriver().get_driver())
            # 点击登录连接
            cls.login.page_click_login_link()
        except Exception as e:
            log.error(e)

    # tearDown
    @classmethod
    def tearDownClass(cls):
        sleep(3)
        # 关闭 driver驱动对象
        GetDriver().quit_driver()

    def tearDown(self):
        self.login.driver.refresh()

    # 登录测试方法
    @parameterized.expand(get_data())
    def test_login(self, username, pwd, code, expect_result, success):
        # 调用登录方法
        self.login.page_login(username, pwd, code)
        if success:
            try:
                # 判断安全退出是否存在
                self.assertTrue(self.login.page_is_login_success())
                # 点击退出
                self.login.page_click_logout()
                try:
                    # 判断登录是否存在
                    self.assertTrue(self.login.page_is_logout_success)
                except:
                    # 截图
                    self.login.page_get_img()
                # 点击登录连接
                self.login.page_click_login_link()
            except Exception as e:
                # 截图
                self.login.page_get_img()
                log.error(e)
        else:
            # 获取登录提示信息
            msg = self.login.page_get_error_info()
            try:
                # 断言
                self.assertEqual(msg, expect_result)

            except AssertionError:
                # 截图
                self.login.page_get_img()
            # 点击 确认框
            self.login.page_click_err_btn_ok()

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值