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()
相关推荐
q56731523几秒前
IBM官网新闻爬虫代码示例
开发语言·分布式·爬虫
DanCheng-studio2 分钟前
毕设 基于机器视觉的驾驶疲劳检测系统(源码+论文)
python·毕业设计·毕设
carpell4 分钟前
【语义分割专栏】3:Segnet实战篇(附上完整可运行的代码pytorch)
人工智能·python·深度学习·计算机视觉·语义分割
笨笨马甲6 分钟前
附加模块--Qt OpenGL模块功能及架构
开发语言·qt
一只小波波呀1 小时前
打卡第48天
python
钮钴禄·爱因斯晨1 小时前
Java 面向对象进阶之多态:从概念到实践的深度解析
java·开发语言·数据结构
zstar-_1 小时前
一套个人知识储备库构建方案
python
鸽子炖汤1 小时前
Java中==和equals的区别
java·开发语言·jvm
有个傻瓜1 小时前
PHP语言核心技术全景解析
开发语言·kubernetes·php
Amo Xiang1 小时前
《100天精通Python——基础篇 2025 第5天:巩固核心知识,选择题实战演练基础语法》
python·选择题·基础语法