python 输出日志配置

日志配置

  • 创建log_util.py 文件
  • 使用的地方导入 logger对象,调用对应的日志输出方法
import logging
import os

from logging.handlers import RotatingFileHandler

# 绑定绑定句柄到logger对象
logger = logging.getLogger(__name__)
# 获取当前工具文件所在的路径
root_path = os.path.dirname(os.path.abspath(__file__))
# 拼接当前要输出日志的路径
log_dir_path = os.sep.join([root_path, f'/logs'])
if not os.path.isdir(log_dir_path):
    os.mkdir(log_dir_path)
# 创建日志记录器,指明日志保存路径,每个日志的大小,保存日志的上限
file_log_handler = RotatingFileHandler(os.sep.join([log_dir_path, 'log.log']), maxBytes=1024 * 1024, backupCount=10 , encoding="utf-8")
# 设置日志的格式
date_string = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(
    '[%(asctime)s] [%(levelname)s] [%(filename)s]/[line: %(lineno)d]/[%(funcName)s] %(message)s ', date_string)
# 日志输出到控制台的句柄
stream_handler = logging.StreamHandler()
# 将日志记录器指定日志的格式
file_log_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)
# 为全局的日志工具对象添加日志记录器
# 绑定绑定句柄到logger对象
logger.addHandler(stream_handler)
logger.addHandler(file_log_handler)
# 设置日志输出级别
logger.setLevel(level=logging.INFO)
import logging
import os
from logging.handlers import RotatingFileHandler

import pytest

from CalculatorProject.script.calculator import Calculator


class Logging():
    # 绑定绑定句柄到logger对象
    logger = logging.getLogger(__name__)
    # 获取当前工具文件所在的路径
    root_path = os.path.dirname(os.path.abspath(__file__))
    # 拼接当前要输出日志的路径
    log_dir_path = os.sep.join([root_path, f'/logs'])
    if not os.path.isdir(log_dir_path):
        os.mkdir(log_dir_path)
    # 创建日志记录器,指明日志保存路径,每个日志的大小,保存日志的上限
    file_log_handler = RotatingFileHandler(os.sep.join([log_dir_path, 'log.log']), maxBytes=1024 * 1024, backupCount=10)
    # 设置日志的格式
    date_string = '%Y-%m-%d %H:%M:%S'
    formatter = logging.Formatter(
        '[%(asctime)s] [%(levelname)s] [%(filename)s]/[line: %(lineno)d]/[%(funcName)s] %(message)s ', date_string)
    # 日志输出到控制台的句柄
    stream_handler = logging.StreamHandler()
    # 将日志记录器指定日志的格式
    file_log_handler.setFormatter(formatter)
    stream_handler.setFormatter(formatter)
    # 为全局的日志工具对象添加日志记录器
    # 绑定绑定句柄到logger对象
    logger.addHandler(stream_handler)
    logger.addHandler(file_log_handler)
    # 设置日志输出级别
    logger.setLevel(level=logging.INFO)

class TestAdd:
    # 实例化一个Calculator()实例
    calc = Calculator()

    def setup(self):
        print("开始计算")

    def teardown(self):
        print("结束计算")

    def teardown_class(self):
        print("退出计算")

    @pytest.mark.addP0
    @pytest.mark.parametrize("x,y,excepted", [[1, 1, 2], [-0.01, 0.02, 0.01], [10, 0.02, 10.02]])
    def test_add_001(self, x, y, excepted):
        result = self.calc.add(x, y)
        logging.info(f"结果为{result}")
        assert result == excepted

    @pytest.mark.addP1Ture
    @pytest.mark.parametrize("x,y,excepted", [[98.99, 99, 197.99], [99, 98.99, 0197.99], [-98.99, -99, -197.99],
                                              [-99, -98.99, -197.99]])
    def test_add_002(self, x, y, excepted):
        result = self.calc.add(x, y)
        logging.info(f"结果为{result}")
        assert result == excepted

    @pytest.mark.addP1Falsea
    @pytest.mark.parametrize("x,y,excepted", [[99.01, 0, "参数大小超出范围"], [-99.01, -1, "参数大小超出范围"],
                                              [2, 99.01, "参数大小超出范围"], [1, -99.01, "参数大小超出范围"]],ids=["add_008","add_009","add_0010","add_0011"])
    def test_add_003(self, x, y, excepted):
        result = self.calc.add(x, y)
        logging.info(f"结果为{result}")
        assert result == excepted

    @pytest.mark.addP1False2
    @pytest.mark.parametrize("x,y,excepted", [["加", 0, "参数大小超出范围"], [-99.01, "加", "参数大小超出范围"]])
    def test_add_004(self, x, y, excepted):
        try:
            result = self.calc.add(x, y)
        except TypeError as e:
            logging.info(f"类型错误{e}")

from question import Calculator
import pytest
class Testcaculator():
    cal = Calculator()
    def setup(self):
        print('开始')
    def teardown(self):
        print('结束')
    def teardown_class(self):
        print('结束类')
    @pytest.mark.parametrize('a,b,c',[(1,1,2),(-0.01,0.02,0.01),(10,0.02,10.02),(98.99,99,197.99),
                                      (99,98.99,197.99),(-99,-98.99,-197.99),
                                      (-98.99,-99,-197.99),(99.01,0,'参数大小超出范围'),
                                      (-99.01,-1,'参数大小超出范围'),(2,99.01,'参数大小超出范围'),
                                      (1,-99.01,'参数大小超出范围'),('文',9.3,'参数大小超出范围'),
                                      (4,'文','参数大小超出范围')])
    def test_all(self,a,b,c):
        result=self.cal.add(a,b)
        expend=c
        assert result==expend