利用Python的logging模块将日志写入不同文件

import os
import logging
from logging.handlers import RotatingFileHandler

class LOG(object):
    def __init__(self):
        self.dir = os.path.dirname(__file__)
        self.__loggers = {}
        handlers = {
                logging.INFO: os.path.join(self.dir, 'log1.log'),
                logging.DEBUG: os.path.join(self.dir, 'log2.log'),
            }
        formatter = logging.Formatter('[%(asctime)s] - [%(levelname)-4s] - %(message)s')

        for level in handlers.keys():
            path = os.path.abspath(handlers[level])
            handlers[level] = RotatingFileHandler(path, maxBytes=1024*1024*2, backupCount=5, encoding='utf-8')
            handlers[level].setFormatter(formatter)

            logger = logging.getLogger(str(level))
            logger.addHandler(handlers[level])
            logger.setLevel(level)
            self.__loggers.update({level: logger})
            
    def info(self, message):
        self.__loggers[logging.INFO].info(message)

    def debug(self, message):
        self.__loggers[logging.DEBUG].debug(message)

if __name__ == "__main__":
    logger = LOG()
    logger.debug("This is the debug message")
    logger.info("This is the info message")

上述代码自定义了一个日志类:‘LOG’,它使用了Python的logging模块和RotatingFileHandler,具体分析如下:

  • init 方法中,初始化了 self.dir 属性,表示日志文件的保存路径。self.__loggers 是一个字典,用于存储不同级别的日志记录器。
  • handlers 是一个字典,将不同的日志级别映射到相应的日志文件路径。在这个示例中,将 logging.INFO 映射到 ‘log1.log’,将 logging.DEBUG 映射到 ‘log2.log’。
  • 创建一个 logging.Formatter 对象 formatter,用于设置日志消息的格式。
  • 遍历 handlers 字典的键(即日志级别),对于每个级别:
    • 使用 os.path.join 将保存路径和日志文件名组合成完整的文件路径。
    • 创建 RotatingFileHandler 对象,其中使用了设置的文件路径,maxBytes 参数设置单个日志文件的最大大小为 2MB,backupCount 参数设置保留的历史日志文件数量为 5,encoding 参数设置文件编码为 UTF-8。
    • 将格式化器设置给处理程序。
    • 创建一个 logging.Logger 对象,并将处理程序添加到该记录器中。然后将该记录器添加到 self.__loggers 字典中,以便以后使用。
  • info 方法和 debug 方法分别通过 self.__loggers 字典来记录相应级别的日志消息。这些方法使用 logging.INFO 和 logging.DEBUG 作为键来获取对应级别的记录器,并调用 info 和 debug 方法记录日志消息。

总结:该代码的作用是封装了一个自定义的日志类 LOG,它将不同级别的日志消息记录到不同的文件中。使用了 RotatingFileHandler 来管理日志文件的轮换和大小控制。在使用 LOG 类时,可以通过调用 info 和 debug 方法记录相应级别的日志消息。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值