写日志到本地文件
1、封装成一个类class
import os
import time
import loggingclass LogManager:def __init__(self, log_file_path, max_days=7):self.log_file_path = log_file_pathself.max_days = max_daysself.logger = self._setup_logger()def _setup_logger(self):logger = logging.getLogger(__name__)logger.setLevel(logging.INFO)formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')file_handler = logging.FileHandler(self.log_file_path)file_handler.setFormatter(formatter)logger.addHandler(file_handler)return loggerdef _delete_old_logs(self):if not os.path.exists(self.log_file_path):returncurrent_time = time.time()day_seconds = 24 * 60 * 60max_seconds = self.max_days * day_secondsfile_stat = os.stat(self.log_file_path)if current_time - file_stat.st_mtime > max_seconds:os.remove(self.log_file_path)def log(self, message):self._delete_old_logs()self.logger.info(message)
2、在另一个类中调用
from LogManager import LogManager
# 导入 LogManager.py 文件中的 LogManager 类if __name__ == '__main__':log_manager = LogManager('test.log')log_manager.log('这是一条测试日志')