栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python编写多功能日志模块

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python编写多功能日志模块

导入相关库文件:

import logging
import time
import os
import shutil
import re

from logging.handlers import RotatingFileHandler

完整的日志模块:

import logging
import time
import os
import shutil
import re

from logging.handlers import RotatingFileHandler


class Logger(object):
    """
    type_name为日志所在文件夹名字, log_content为要保留日志文件夹数量
    """
    def __init__(self, type_name, log_content):
        self.type_name = type_name
        self.log_path, self.path = self.log_start()
        self.date_path = os.path.dirname(self.path)
        self.all_path = os.path.dirname(self.date_path)
        self.log_content = log_content
        self.del_log()

    """
    path为存放日志的文件夹目录
    log_path为日志文件的完整路径
    """
    def log_start(self):
        loacl_time = time.strftime("%Y_%m_%d", time.localtime())
        complete_time = time.strftime("%Y_%m_%d_%H_%M_%S",time.localtime())
        # path = os.path.join(os.getcwd(), "LOG", loacl_time) + "_" + self.type_name + ".log"
        path = os.path.join(os.getcwd(), "LOG", loacl_time, self.type_name)
        if not os.path.exists(path):
            os.makedirs(path)
        log_path = os.path.join(path , "%s_"%self.type_name) + complete_time +".log"
        file_log = open(log_path, "a")
        print(log_path, path)
        return log_path, path

    """
    设置每份日志最大内存为maxBytes=1024 * 10, 超过该内存自动将日志切割到新日志文件中,
    设置backupCount=5,如切割造成新增的日志数量超过五个,自动将五个中旧的日志删除,保留最新的日志并数量保持为五个
    """
    def log_main(self, sign, information):
        write_time = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
        logger = logging.getLogger('mylogger')
        logger.setLevel(level=logging.DEBUG)
        fmt = '%(asctime)s - %(levelname)s : %(message)s'
        format_str = logging.Formatter(fmt)
        fh = RotatingFileHandler(self.log_path, maxBytes=1024 * 10, backupCount=5, encoding="utf-8")
        fh.namer = lambda x: self.path + r"%s_%s_"%(self.type_name, write_time) + x.split(".")[-1] + ".log"  # 这里给namer赋值一个方法,注意后边的.1.2.3是一起传递过来的

        fh.setFormatter(fmt=format_str)
        logger.addHandler(fh)

        if sign == "debug":
            logger.debug(information)
        if sign == "info":
            logger.info(information)
        if sign == "warning":
            logger.warning(information)
        if sign == "error":
            logger.error(information)
        if sign == "critical":
            logger.critical(information)

        logger.removeHandler(fh)


    """
    删除超过保留数量的日志文件夹,
    例如log_content设置为30,日志文件夹超过30个时就会删除多余的日志文件夹,
    让日志文件夹始终保持30个
    """
    def del_log(self):
        if not os.listdir(self.all_path):
            return
        print(os.listdir(self.all_path))
        date_list = []
        for file_name in os.listdir(self.all_path):
            if re.fullmatch(r"d{4}_d{2}_d{2}",file_name):
                all_name = os.path.join(self.all_path, file_name)
                date_list.append(all_name)
        print(date_list)
        # exit()
        if len(date_list) > self.log_content:
            difference_value = len(date_list) - self.log_content
            date_list.sort()
        # exit()
            for i in range(difference_value):
                shutil.rmtree(date_list[i], ignore_errors=True)
                if os.path.isfile(date_list[i]):
                    os.remove(date_list[i])
                else:
                    pass

    """
    编写五种报告类型的函数
    """
    def Debug(self, information):
        sign = "debug"
        self.log_main(sign, information)

    def Info(self, information):
        sign = "info"
        self.log_main(sign, information)

    def Warning(self, information):
        sign = "warning"
        self.log_main(sign, information)

    def Error(self,information):
        sign = "error"
        self.log_main(sign, information)

    def Critical(self,information):
        sign = "critical"
        self.log_main(sign, information)

调用方法:

if __name__ == '__main__':
    """
    先实例化再进行调用日志模块
    """
    logger = Logger("Business",2)
    for i in range(240):
        logger.Info("zhangsan")
        logger.Warning("1111111")

这个日志模块功能很强大,读者可以使用这个日志模块来记录程序的运行过程,本模块编写不容易,望读者给予个大大的赞。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/461604.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号