为了创建一个Python类来管理日志,并使其支持按日期分割日志文件(每天一个新的日志文件),你可以使用Python标准库中的logging模块和logging.handlers.TimedRotatingFileHandler。下面是一个简单的示例,展示了如何实现这个需求。
首先,你需要安装Python(如果尚未安装)。然后,可以创建一个名为log_manager.py的Python文件,并在其中定义你的日志管理类。
import logging
from logging.handlers import TimedRotatingFileHandler
import os
class LogManager:
def __init__(self, log_dir, log_name):
"""
初始化日志管理器
:param log_dir: 日志文件存储的目录
:param log_name: 日志文件的基本名称,日期会被追加到文件名中
"""
self.log_dir = log_dir
self.log_name = log_name
self.setup_logger()
def setup_logger(self):
"""
配置并启动日志记录器
"""
# 确保日志目录存在
if not os.path.exists(self.log_dir):
os.makedirs(self.log_dir)
# 创建日志记录器
self.logger = logging.getLogger(self.log_name)
self.logger.setLevel(logging.DEBUG) # 可以根据需要调整日志级别
# 创建一个handler,用于写入日志文件,每天滚动一次
log_file_path = os.path.join(self.log_dir, self.log_name + ".log")
handler = TimedRotatingFileHandler(log_file_path, when="midnight", backupCount=7)
# 创建日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# 给logger添加handler
self.logger.addHandler(handler)
def debug(self, message):
"""
记录调试信息
"""
self.logger.debug(message)
def info(self, message):
"""
记录普通信息
"""
self.logger.info(message)
def warning(self, message):
"""
记录警告信息
"""
self.logger.warning(message)
def error(self, message):
"""
记录错误信息
"""
self.logger.error(message)
def critical(self, message):
"""
记录严重错误信息
"""
self.logger.critical(message)
# 使用示例
if __name__ == "__main__":
log_manager = LogManager("/path/to/your/logs", "myapp")
log_manager.info("This is an info message.")
log_manager.warning("This is a warning message.")
在上面的代码中,LogManager类负责设置和管理日志记录器。它使用TimedRotatingFileHandler来确保日志文件每天滚动一次,并且只保留最近的7个日志文件(通过backupCount=7设置)。
- 你需要将
"/path/to/your/logs"替换为你希望存储日志文件的实际路径。 log_name是你希望日志文件使用的基本名称,日期和时间戳会被自动添加到文件名中。
这样,你就可以在你的程序中的任何位置通过实例化LogManager类并调用其方法来记录日志了,而无需担心日志文件的创建、滚动和删除问题。










