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()
相关推荐
lsx202406几秒前
SVN 创建版本库
开发语言
xiaotao1313 分钟前
01-编程基础与数学基石:Python错误与异常处理
开发语言·人工智能·python
2401_835956815 分钟前
mysql处理大量更新场景_InnoDB MVCC与MyISAM对比
jvm·数据库·python
m0_7489203615 分钟前
Oracle默认端口被占用如何连接_修改端口号操作教程
jvm·数据库·python
YummyJacky16 分钟前
Hermes Agent自进化的实现方式
人工智能·python
qq_3422958222 分钟前
Redis怎样按照距离远近排序展示_通过GEORADIUS的ASC参数进行Geo排序
jvm·数据库·python
2201_7610405928 分钟前
C#比较两个二进制文件的差异 C#如何实现一个二进制diff工具
jvm·数据库·python
Csvn35 分钟前
🌟 LangChain 30 天保姆级教程 · Day 23|Agent 进阶实战!Function Calling + 自动 Tool 注册,打造会“动
python·langchain
Csvn35 分钟前
🌟 LangChain 30 天保姆级教程 · Day 22|长文档处理三剑客!MapReduce、Refine、Map-Rerank,让 AI 消化整本手册
python·langchain
皮卡蛋炒饭.1 小时前
线程的概念和控制
java·开发语言·jvm