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()
相关推荐
Niuguangshuo3 分钟前
DeepFilterNet 3:端侧实时全带降噪的开源标杆
python
第一程序员20 分钟前
AI 辅助编程的 7 个误区:把模型当高级搜索引擎是对它的最大浪费
python·rust·github
16月6日-晴37 分钟前
Java面向对象进阶—多态
java·开发语言
冯汉栩1 小时前
Swift Control RollingCountdownView(动画倒计时)
开发语言·ios·swift
lisanmengmeng1 小时前
搭建elk环境并接入frostmourne,实现监控报警效果(五)
开发语言·elk·日志·日志监控
Groundwork Explorer2 小时前
W5500 网卡编程初始化与使用指南
python·单片机
oh,huoyuyan2 小时前
JS 动态网页抓不到?试试火车采集器网页抓取工具
开发语言·javascript·ecmascript
风流 少年2 小时前
hutool
java·服务器·开发语言
逸Y 仙X2 小时前
MCP(模型控制协议)完全指南:从核心概念到实战开发
python·大模型·llm·ai编程·mcp
一木 之林3 小时前
四、STL容器与数据结构
开发语言·数据结构·c++