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()
相关推荐
剑桥折刀s3 分钟前
Python打卡:Day46
python
巴里巴气25 分钟前
Python爬虫图片验证码和滑块验证码识别总结
爬虫·python
尘世闲鱼1 小时前
解数独(C++版本)
开发语言·c++·算法·解数独
sword devil9001 小时前
PYQT实战:智能家居中控
python·智能家居·pyqt
NetX行者1 小时前
FastMCP:用于构建MCP服务器的开源Python框架
服务器·python·开源
超龄超能程序猿1 小时前
(3)机器学习小白入门 YOLOv: 解锁图片分类新技能
python·numpy·pandas·scipy
waynaqua1 小时前
FastAPI开发AI应用一:实现连续多轮对话
python·openai
纨妙2 小时前
python打卡day59
开发语言·python
waynaqua2 小时前
FastAPI开发AI应用二:多厂商模型使用指南
python·openai
秋难降2 小时前
Python 知识 “八股”:给有 C 和 Java 基础的你😁😁😁
java·python·c