[Pytest] [Part 2]增加 log功能

开始实现需求之前先做个log类,可以给其他模块使用,也方便以后修改log类的功能和属性。

使用的是python中的logging包来进行简单的封装,具体代码如下

python 复制代码
import logging
import sys


class TefLogger:

    def __init__(self, logger_name='TEST_FRAMEWORK'):
        self.logger = logging.getLogger(logger_name)
        self.logger.propagate = False
        self.set_level(logging.DEBUG)
        self.formatter = logging.Formatter('%(asctime)s - %(module)s - %(lineno)s - %(levelname)s - %(message)s',
                                           datefmt='%m/%d/%Y %I:%M:%S %p')

    def set_level(self, level=logging.DEBUG):
        self.logger.setLevel(level)

    def add_stream_handler(self, level=logging.INFO):
        self.stdout_log_handler = logging.StreamHandler(sys.stdout)
        self.stdout_log_handler.setLevel(level)
        self.stdout_log_handler.setFormatter(self.formatter)
        self.logger.addHandler(self.stdout_log_handler)
        return self.stdout_log_handler

    def add_file_handler(self, log_file_name, level=logging.INFO):
        file_log_handler = logging.FileHandler(log_file_name, 'w', 'utf-8')
        file_log_handler.setFormatter(self.formatter)
        file_log_handler.setLevel(level)
        self.logger.addHandler(file_log_handler)
        return file_log_handler

    def get_logger(self):
        return self.logger

    def remove_handler(self, log_handler):
        self.logger.removeHandler(log_handler)

#USAGE EXAMPLE 

'''
teflog = TefLogger()
teflog.add_stream_handler(logging.DEBUG)
teflog.add_file_handler('test_info.txt', logging.INFO)
teflog.add_file_handler('test_debug.txt', logging.DEBUG)
logger = teflog.get_logger()

logger.info("test_info")
logger.debug("test_debug")
'''

这样的话以后在新建类的__init__中可以实例化logger类来使用

相关推荐
兵慌码乱3 小时前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei6 小时前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
aqi0012 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn13 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi002 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵2 天前
用 Python 实现 Take-Away 游戏
python·游戏