[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类来使用

相关推荐
future14121 小时前
C#学习日记
开发语言·学习·c#
菜包eo1 小时前
二维码驱动的独立站视频集成方案
网络·python·音视频
Yo_Becky1 小时前
【PyTorch】PyTorch预训练模型缓存位置迁移,也可拓展应用于其他文件的迁移
人工智能·pytorch·经验分享·笔记·python·程序人生·其他
king_harry1 小时前
Java程序-OceanBase Connector/J 示例
开发语言
yzx9910131 小时前
关于网络协议
网络·人工智能·python·网络协议
fangeqin1 小时前
ubuntu源码安装python3.13遇到Could not build the ssl module!解决方法
linux·python·ubuntu·openssl
傻啦嘿哟2 小时前
Python 办公实战:用 python-docx 自动生成 Word 文档
开发语言·c#
翻滚吧键盘2 小时前
js代码09
开发语言·javascript·ecmascript
Jay Kay2 小时前
TensorFlow源码深度阅读指南
人工智能·python·tensorflow
q567315232 小时前
R语言初学者爬虫简单模板
开发语言·爬虫·r语言·iphone