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

相关推荐
geovindu2 小时前
go: Visitor Pattern
开发语言·设计模式·golang·访问者模式
宣宣猪的小花园.2 小时前
C语言重难点全解析:内存管理到位运算
c语言·开发语言·单片机
方安乐6 小时前
python之向量、向量和、向量点积
开发语言·python·numpy
zh1570238 小时前
JavaScript中WorkerThreads解决服务端计算瓶颈
jvm·数据库·python
小小小米粒8 小时前
Collection单列集合、Map(Key - Value)双列集合,多继承实现。
java·开发语言·windows
蜡台8 小时前
Python包管理工具pip完全指南-----2
linux·windows·python
Mr.朱鹏8 小时前
【Python 进阶 | 第四篇】Psycopg3 + Flask 实现 PostgreSQL CRUD 全流程:从连接池到RESTful接口
python·postgresql·flask·virtualenv·fastapi·pip·tornado
czhc11400756639 小时前
C# 428 线程、异步
开发语言·c#
2401_871492859 小时前
Vue.js监听器watch利用回调函数处理级联下拉框数据联动
jvm·数据库·python
FreakStudio9 小时前
亲测可用!可本地部署的 MicroPython 开源仿真器
python·单片机·嵌入式·面向对象·并行计算·电子diy·电子计算机