|
| 1 | +import codecs |
| 2 | +import os |
| 3 | +import re |
| 4 | +import time |
| 5 | +from datetime import datetime |
| 6 | +from logging.handlers import BaseRotatingHandler, TimedRotatingFileHandler |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +"""自定义日志处理器模块: |
| 10 | +该模块包含FastDeploy项目中使用的自定义日志处理器实现, |
| 11 | +用于处理和控制日志输出格式、级别和目标等。 |
| 12 | +""" |
| 13 | + |
| 14 | + |
| 15 | +class DailyFolderTimedRotatingFileHandler(TimedRotatingFileHandler): |
| 16 | + """ |
| 17 | + 自定义处理器:每天一个目录,每小时一个文件 |
| 18 | + 文件结构: |
| 19 | + logs/ |
| 20 | + └── 2025-08-05/ |
| 21 | + ├── fastdeploy_error_10.log |
| 22 | + └── fastdeploy_debug_10.log |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__(self, filename, when="H", interval=1, backupCount=48, encoding=None, utc=False, **kwargs): |
| 26 | + # 支持从dictConfig中通过filename传入 base_log_dir/base_filename |
| 27 | + base_log_dir, base_name = os.path.split(filename) |
| 28 | + base_filename = os.path.splitext(base_name)[0] |
| 29 | + |
| 30 | + self.base_log_dir = base_log_dir |
| 31 | + self.base_filename = base_filename |
| 32 | + self.current_day = datetime.now().strftime("%Y-%m-%d") |
| 33 | + self._update_baseFilename() |
| 34 | + |
| 35 | + super().__init__( |
| 36 | + filename=self.baseFilename, |
| 37 | + when=when, |
| 38 | + interval=interval, |
| 39 | + backupCount=backupCount, |
| 40 | + encoding=encoding, |
| 41 | + utc=utc, |
| 42 | + ) |
| 43 | + |
| 44 | + def _update_baseFilename(self): |
| 45 | + dated_dir = os.path.join(self.base_log_dir, self.current_day) |
| 46 | + os.makedirs(dated_dir, exist_ok=True) |
| 47 | + self.baseFilename = os.path.abspath( |
| 48 | + os.path.join(dated_dir, f"{self.base_filename}_{datetime.now().strftime('%H')}.log") |
| 49 | + ) |
| 50 | + |
| 51 | + def shouldRollover(self, record): |
| 52 | + new_day = datetime.now().strftime("%Y-%m-%d") |
| 53 | + if new_day != self.current_day: |
| 54 | + self.current_day = new_day |
| 55 | + return 1 |
| 56 | + return super().shouldRollover(record) |
| 57 | + |
| 58 | + def doRollover(self): |
| 59 | + self.stream.close() |
| 60 | + self._update_baseFilename() |
| 61 | + self.stream = self._open() |
| 62 | + |
| 63 | + |
| 64 | +class DailyRotatingFileHandler(BaseRotatingHandler): |
| 65 | + """ |
| 66 | + like `logging.TimedRotatingFileHandler`, but this class support multi-process |
| 67 | + """ |
| 68 | + |
| 69 | + def __init__( |
| 70 | + self, |
| 71 | + filename, |
| 72 | + backupCount=0, |
| 73 | + encoding="utf-8", |
| 74 | + delay=False, |
| 75 | + utc=False, |
| 76 | + **kwargs, |
| 77 | + ): |
| 78 | + """ |
| 79 | + 初始化 RotatingFileHandler 对象。 |
| 80 | +
|
| 81 | + Args: |
| 82 | + filename (str): 日志文件的路径,可以是相对路径或绝对路径。 |
| 83 | + backupCount (int, optional, default=0): 保存的备份文件数量,默认为 0,表示不保存备份文件。 |
| 84 | + encoding (str, optional, default='utf-8'): 编码格式,默认为 'utf-8'。 |
| 85 | + delay (bool, optional, default=False): 是否延迟写入,默认为 False,表示立即写入。 |
| 86 | + utc (bool, optional, default=False): 是否使用 UTC 时区,默认为 False,表示不使用 UTC 时区。 |
| 87 | + kwargs (dict, optional): 其他参数将被传递给 BaseRotatingHandler 类的 init 方法。 |
| 88 | +
|
| 89 | + Raises: |
| 90 | + TypeError: 如果 filename 不是 str 类型。 |
| 91 | + ValueError: 如果 backupCount 小于等于 0。 |
| 92 | + """ |
| 93 | + self.backup_count = backupCount |
| 94 | + self.utc = utc |
| 95 | + self.suffix = "%Y-%m-%d" |
| 96 | + self.base_log_path = Path(filename) |
| 97 | + self.base_filename = self.base_log_path.name |
| 98 | + self.current_filename = self._compute_fn() |
| 99 | + self.current_log_path = self.base_log_path.with_name(self.current_filename) |
| 100 | + BaseRotatingHandler.__init__(self, filename, "a", encoding, delay) |
| 101 | + |
| 102 | + def shouldRollover(self, record): |
| 103 | + """ |
| 104 | + check scroll through the log |
| 105 | + """ |
| 106 | + if self.current_filename != self._compute_fn(): |
| 107 | + return True |
| 108 | + return False |
| 109 | + |
| 110 | + def doRollover(self): |
| 111 | + """ |
| 112 | + scroll log |
| 113 | + """ |
| 114 | + if self.stream: |
| 115 | + self.stream.close() |
| 116 | + self.stream = None |
| 117 | + |
| 118 | + self.current_filename = self._compute_fn() |
| 119 | + self.current_log_path = self.base_log_path.with_name(self.current_filename) |
| 120 | + |
| 121 | + if not self.delay: |
| 122 | + self.stream = self._open() |
| 123 | + |
| 124 | + self.delete_expired_files() |
| 125 | + |
| 126 | + def _compute_fn(self): |
| 127 | + """ |
| 128 | + Calculate the log file name corresponding current time |
| 129 | + """ |
| 130 | + return self.base_filename + "." + time.strftime(self.suffix, time.localtime()) |
| 131 | + |
| 132 | + def _open(self): |
| 133 | + """ |
| 134 | + open new log file |
| 135 | + """ |
| 136 | + if self.encoding is None: |
| 137 | + stream = open(str(self.current_log_path), self.mode) |
| 138 | + else: |
| 139 | + stream = codecs.open(str(self.current_log_path), self.mode, self.encoding) |
| 140 | + |
| 141 | + if self.base_log_path.exists(): |
| 142 | + try: |
| 143 | + if not self.base_log_path.is_symlink() or os.readlink(self.base_log_path) != self.current_filename: |
| 144 | + os.remove(self.base_log_path) |
| 145 | + except OSError: |
| 146 | + pass |
| 147 | + |
| 148 | + try: |
| 149 | + os.symlink(self.current_filename, str(self.base_log_path)) |
| 150 | + except OSError: |
| 151 | + pass |
| 152 | + return stream |
| 153 | + |
| 154 | + def delete_expired_files(self): |
| 155 | + """ |
| 156 | + delete expired log files |
| 157 | + """ |
| 158 | + if self.backup_count <= 0: |
| 159 | + return |
| 160 | + |
| 161 | + file_names = os.listdir(str(self.base_log_path.parent)) |
| 162 | + result = [] |
| 163 | + prefix = self.base_filename + "." |
| 164 | + plen = len(prefix) |
| 165 | + for file_name in file_names: |
| 166 | + if file_name[:plen] == prefix: |
| 167 | + suffix = file_name[plen:] |
| 168 | + if re.match(r"^\d{4}-\d{2}-\d{2}(\.\w+)?$", suffix): |
| 169 | + result.append(file_name) |
| 170 | + if len(result) < self.backup_count: |
| 171 | + result = [] |
| 172 | + else: |
| 173 | + result.sort() |
| 174 | + result = result[: len(result) - self.backup_count] |
| 175 | + |
| 176 | + for file_name in result: |
| 177 | + os.remove(str(self.base_log_path.with_name(file_name))) |
0 commit comments