python log tool封装

python log tool 封装

python 复制代码
# _*_ encoding:utf-8 _*_
import logging
from io import StringIO
from datetime import datetime
import os


class Log:
    stringIo = StringIO()
    fileNameLogging = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + "/c_log/testLogging.log"
    fileNameIO = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + "/c_log/testLogIO.log"
    fileNameFile = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + "/c_log/testLogFile.log"

    # 通过python系统自带的logging模块,将信息写入log文件
    @classmethod
    def log(cls):
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(filename)s [line: %(lineno)d] - %(levelname)s: %(message)s')

        # # # set screen print output
        # # screen_handler = logging.StreamHandler()        # 初始化控制台处理器输出对象
        # # screen_handler.setFormatter(formatter)          # 设置控制台处理器输出格式
        # # logger.addHandler(screen_handler)               # 记录器添加控制台处理器

        # # set log file and save
        file_handler = logging.FileHandler(filename=cls.fileNameLogging, mode='a', encoding='utf-8')  # 初始化文件log处理器输出对象
        file_handler.setFormatter(formatter)  # 设置文件处理器输出格式
        logger.addHandler(file_handler)  # 记录器添加文件处理器

        return logger


    # 直接经信息写入StringIO的内存
    @classmethod
    def logIO(cls, msg):
        message = str(datetime.now()) + " msg: " + str(msg) + "\n"
        cls.stringIo.write(message)
        cls.stringIo.flush()

    # 将StringIO信息一次性写入log文件
    @classmethod
    def logWrite(cls):
        cls.stringIo.seek(0, 0)

        for line in cls.stringIo.readlines():
            with open(cls.fileNameIO, mode="a", encoding="utf-8") as f:
                f.write(line)
                f.flush()

    # 直接经信息写入log文档
    @classmethod
    def logfile(cls, msg):
        message = str(datetime.now()) + " msg: " + str(msg) + "\n"
        with open(cls.fileNameFile, mode="a", encoding="utf-8") as f:
            f.write(message)
            f.flush()


if __name__ == '__main__':
    Log.log().info("aaa")
    Log.logIO("write the string io============cccccc=============================")
    # Log.logWrite()
    Log.logIO("write the string io============aaaaaaaaaaa========================")
    Log.logWrite()
相关推荐
用户8356290780514 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下4 小时前
最终的信号类
开发语言·c++·算法
c8i4 小时前
python中类的基本结构、特殊属性于MRO理解
python
echoarts5 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
liwulin05065 小时前
【ESP32-CAM】HELLO WORLD
python
Aomnitrix5 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
Doris_20235 小时前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_20235 小时前
Python 模式匹配match case
前端·后端·python
每天回答3个问题5 小时前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说6 小时前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox