prolog-py 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- prolog/__init__.py +55 -0
- prolog/_version.py +3 -0
- prolog/binary.py +481 -0
- prolog/core.py +120 -0
- prolog/formatters.py +218 -0
- prolog/gui_output.py +734 -0
- prolog/handlers.py +386 -0
- prolog/levels.py +62 -0
- prolog/locking.py +98 -0
- prolog/logger.py +144 -0
- prolog/py.typed +0 -0
- prolog/record.py +86 -0
- prolog_py-1.0.0.dist-info/METADATA +306 -0
- prolog_py-1.0.0.dist-info/RECORD +17 -0
- prolog_py-1.0.0.dist-info/WHEEL +5 -0
- prolog_py-1.0.0.dist-info/licenses/LICENSE +21 -0
- prolog_py-1.0.0.dist-info/top_level.txt +1 -0
prolog/__init__.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from prolog._version import __version__, __author__, __license__
|
|
2
|
+
from prolog.levels import Level, normalize_level
|
|
3
|
+
from prolog.record import LogRecord
|
|
4
|
+
from prolog.formatters import (
|
|
5
|
+
Formatter,
|
|
6
|
+
TextFormatter,
|
|
7
|
+
JsonFormatter,
|
|
8
|
+
CsvFormatter,
|
|
9
|
+
JsonlFormatter,
|
|
10
|
+
XmlFormatter,
|
|
11
|
+
MarkdownFormatter,
|
|
12
|
+
HtmlFormatter,
|
|
13
|
+
)
|
|
14
|
+
from prolog.handlers import (
|
|
15
|
+
Handler,
|
|
16
|
+
StreamHandler,
|
|
17
|
+
FileHandler,
|
|
18
|
+
RotatingFileHandler,
|
|
19
|
+
TimedRotatingFileHandler,
|
|
20
|
+
BinaryFileHandler,
|
|
21
|
+
AsyncHandler,
|
|
22
|
+
NullHandler,
|
|
23
|
+
)
|
|
24
|
+
from prolog.logger import Logger
|
|
25
|
+
from prolog.binary import recover as recover_plog, verify as verify_plog
|
|
26
|
+
from prolog.core import Prolog
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"__version__",
|
|
30
|
+
"__author__",
|
|
31
|
+
"__license__",
|
|
32
|
+
"Level",
|
|
33
|
+
"normalize_level",
|
|
34
|
+
"LogRecord",
|
|
35
|
+
"Formatter",
|
|
36
|
+
"TextFormatter",
|
|
37
|
+
"JsonFormatter",
|
|
38
|
+
"CsvFormatter",
|
|
39
|
+
"JsonlFormatter",
|
|
40
|
+
"XmlFormatter",
|
|
41
|
+
"MarkdownFormatter",
|
|
42
|
+
"HtmlFormatter",
|
|
43
|
+
"Handler",
|
|
44
|
+
"StreamHandler",
|
|
45
|
+
"FileHandler",
|
|
46
|
+
"RotatingFileHandler",
|
|
47
|
+
"TimedRotatingFileHandler",
|
|
48
|
+
"BinaryFileHandler",
|
|
49
|
+
"AsyncHandler",
|
|
50
|
+
"NullHandler",
|
|
51
|
+
"Logger",
|
|
52
|
+
"Prolog",
|
|
53
|
+
"recover_plog",
|
|
54
|
+
"verify_plog",
|
|
55
|
+
]
|
prolog/_version.py
ADDED
prolog/binary.py
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import struct
|
|
6
|
+
import time
|
|
7
|
+
import zlib
|
|
8
|
+
from typing import Any, Dict, Iterator, List, Optional, Tuple
|
|
9
|
+
|
|
10
|
+
from prolog.locking import FileLock
|
|
11
|
+
|
|
12
|
+
MAGIC = b"PLOG"
|
|
13
|
+
VERSION = 0x0100
|
|
14
|
+
HEADER_SIZE = 64
|
|
15
|
+
_HEADER_FMT = "<4sHHQQQ32s" # 4+2+2+8+8+8+32 = 64
|
|
16
|
+
_HEADER_LEN = struct.calcsize(_HEADER_FMT)
|
|
17
|
+
_RECORD_HEAD_FMT = "<IQB" # length, timestamp_ms, level
|
|
18
|
+
_RECORD_HEAD_LEN = struct.calcsize(_RECORD_HEAD_FMT)
|
|
19
|
+
_CRC_FMT = "<I"
|
|
20
|
+
_CRC_LEN = struct.calcsize(_CRC_FMT)
|
|
21
|
+
_FLAG_COMPRESSED = 0x0001
|
|
22
|
+
|
|
23
|
+
# 单条记录 payload 的合理上限, 超过则视为头部损坏 (防御性)
|
|
24
|
+
_MAX_RECORD = 100 * 1024 * 1024
|
|
25
|
+
# resync 时最多向前扫描的字节数
|
|
26
|
+
_RESYNC_WINDOW = 64 * 1024
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class BinaryLogError(Exception):
|
|
30
|
+
"""二进制日志读写异常。"""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class PlogWriter:
|
|
34
|
+
"""流式写入 .plog 文件, 支持新建与对已有文件追加。"""
|
|
35
|
+
|
|
36
|
+
def __init__(self, fp, compress: bool = True, build_index: bool = True,
|
|
37
|
+
append: bool = False):
|
|
38
|
+
self._fp = fp
|
|
39
|
+
self._compress = compress
|
|
40
|
+
self._build_index = build_index
|
|
41
|
+
self._record_count = 0
|
|
42
|
+
self._index: List[Tuple[int, int]] = []
|
|
43
|
+
self._header_written = False
|
|
44
|
+
self._closed = False
|
|
45
|
+
self._append = append
|
|
46
|
+
if append:
|
|
47
|
+
# 追加模式: 头部已存在, 不再重写占位
|
|
48
|
+
self._header_written = True
|
|
49
|
+
# 整个写入生命周期持独占锁: 跨进程互斥, 同线程可重入
|
|
50
|
+
self._lock = FileLock(fp, "exclusive").acquire()
|
|
51
|
+
|
|
52
|
+
# -- 构造: 自动区分新建 / 追加 ---------------------------------------
|
|
53
|
+
@classmethod
|
|
54
|
+
def open(cls, fp, compress: bool = True, build_index: bool = True):
|
|
55
|
+
"""根据文件当前内容决定新建还是追加 (加独占锁后判断, 无竞态)。
|
|
56
|
+
|
|
57
|
+
返回 (writer, fresh)。fresh=True 表示新建文件。
|
|
58
|
+
"""
|
|
59
|
+
lock = FileLock(fp, "exclusive").acquire()
|
|
60
|
+
try:
|
|
61
|
+
fp.seek(0)
|
|
62
|
+
raw = fp.read(_HEADER_LEN)
|
|
63
|
+
if len(raw) >= _HEADER_LEN and raw[:4] == MAGIC:
|
|
64
|
+
writer = cls(fp, compress=compress, build_index=build_index,
|
|
65
|
+
append=True)
|
|
66
|
+
writer._load_existing(raw)
|
|
67
|
+
return writer, False
|
|
68
|
+
writer = cls(fp, compress=compress, build_index=build_index,
|
|
69
|
+
append=False)
|
|
70
|
+
writer.write_header()
|
|
71
|
+
return writer, True
|
|
72
|
+
except BaseException:
|
|
73
|
+
lock.release()
|
|
74
|
+
raise
|
|
75
|
+
|
|
76
|
+
def _load_existing(self, header_raw: bytes) -> None:
|
|
77
|
+
"""解析已有头部, 恢复记录数/压缩标志/索引, 并定位到追加点。"""
|
|
78
|
+
(magic, version, flags, cnt, created, index_off,
|
|
79
|
+
_) = struct.unpack(_HEADER_FMT, header_raw)
|
|
80
|
+
self._record_count = cnt
|
|
81
|
+
# 追加时沿用原文件的压缩标志, 避免新旧记录解码方式不一致
|
|
82
|
+
self._compress = bool(flags & _FLAG_COMPRESSED)
|
|
83
|
+
self._index = []
|
|
84
|
+
if index_off:
|
|
85
|
+
# 载入旧索引, 并将写指针移动到旧索引起点处覆盖它
|
|
86
|
+
self._load_index(index_off)
|
|
87
|
+
self._fp.seek(index_off)
|
|
88
|
+
else:
|
|
89
|
+
# 无索引: 追加到文件末尾
|
|
90
|
+
self._fp.seek(0, os.SEEK_END)
|
|
91
|
+
|
|
92
|
+
def _load_index(self, offset: int) -> None:
|
|
93
|
+
self._fp.seek(offset)
|
|
94
|
+
raw = self._fp.read(4)
|
|
95
|
+
if len(raw) < 4:
|
|
96
|
+
return
|
|
97
|
+
(count,) = struct.unpack("<I", raw)
|
|
98
|
+
for _ in range(count):
|
|
99
|
+
chunk = self._fp.read(16)
|
|
100
|
+
if len(chunk) < 16:
|
|
101
|
+
break
|
|
102
|
+
off, ts = struct.unpack("<QQ", chunk)
|
|
103
|
+
self._index.append((off, ts))
|
|
104
|
+
|
|
105
|
+
def write_header(self) -> None:
|
|
106
|
+
if self._header_written and not self._append:
|
|
107
|
+
return
|
|
108
|
+
self._fp.seek(0)
|
|
109
|
+
header = struct.pack(
|
|
110
|
+
_HEADER_FMT, MAGIC, VERSION,
|
|
111
|
+
_FLAG_COMPRESSED if self._compress else 0,
|
|
112
|
+
self._record_count, int(time.time() * 1000), 0, b"\x00" * 32,
|
|
113
|
+
)
|
|
114
|
+
self._fp.write(header)
|
|
115
|
+
self._fp.seek(0, os.SEEK_END)
|
|
116
|
+
self._header_written = True
|
|
117
|
+
|
|
118
|
+
def write_record(self, data: Dict[str, Any]) -> None:
|
|
119
|
+
if self._closed:
|
|
120
|
+
raise BinaryLogError("写入器已关闭")
|
|
121
|
+
if not self._header_written:
|
|
122
|
+
self.write_header()
|
|
123
|
+
offset = self._fp.tell()
|
|
124
|
+
raw = json.dumps(data, ensure_ascii=False, default=str).encode("utf-8")
|
|
125
|
+
if self._compress:
|
|
126
|
+
raw = zlib.compress(raw, level=6)
|
|
127
|
+
epoch_ms = int(data.get("epoch_ms", int(time.time() * 1000)))
|
|
128
|
+
level = int(data.get("level_value", 20))
|
|
129
|
+
head = struct.pack(_RECORD_HEAD_FMT, len(raw), epoch_ms, level)
|
|
130
|
+
crc = zlib.crc32(raw) & 0xFFFFFFFF
|
|
131
|
+
self._fp.write(head)
|
|
132
|
+
self._fp.write(raw)
|
|
133
|
+
self._fp.write(struct.pack(_CRC_FMT, crc))
|
|
134
|
+
self._record_count += 1
|
|
135
|
+
if self._build_index:
|
|
136
|
+
self._index.append((offset, epoch_ms))
|
|
137
|
+
|
|
138
|
+
def close(self) -> None:
|
|
139
|
+
if self._closed:
|
|
140
|
+
return
|
|
141
|
+
self._closed = True
|
|
142
|
+
# 写索引块 (追加时覆盖旧索引位置, 内容含新旧全部条目)
|
|
143
|
+
index_offset = 0
|
|
144
|
+
if self._build_index and self._index:
|
|
145
|
+
index_offset = self._fp.tell()
|
|
146
|
+
self._fp.write(struct.pack("<I", len(self._index)))
|
|
147
|
+
for off, ts in self._index:
|
|
148
|
+
self._fp.write(struct.pack("<QQ", off, ts))
|
|
149
|
+
# 回写头部: 更新记录总数与索引偏移 (追加场景的关键修复)
|
|
150
|
+
flags = _FLAG_COMPRESSED if self._compress else 0
|
|
151
|
+
header = struct.pack(
|
|
152
|
+
_HEADER_FMT, MAGIC, VERSION, flags, self._record_count,
|
|
153
|
+
int(time.time() * 1000), index_offset, b"\x00" * 32,
|
|
154
|
+
)
|
|
155
|
+
self._fp.seek(0)
|
|
156
|
+
self._fp.write(header)
|
|
157
|
+
self._fp.flush()
|
|
158
|
+
try:
|
|
159
|
+
self._lock.release()
|
|
160
|
+
except Exception:
|
|
161
|
+
pass
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class PlogReader:
|
|
165
|
+
"""读取 / 查询 .plog 文件, 支持容错读取。"""
|
|
166
|
+
|
|
167
|
+
def __init__(self, fp, strict: bool = False):
|
|
168
|
+
self._fp = fp
|
|
169
|
+
self.strict = strict
|
|
170
|
+
self.errors: List[Dict[str, Any]] = [] # 读取过程中跳过的损坏记录
|
|
171
|
+
self._file_size = self._size_of(fp)
|
|
172
|
+
# 共享锁: 允许多个读取器并发, 与写入器的独占锁互斥
|
|
173
|
+
self._lock = FileLock(fp, "shared").acquire()
|
|
174
|
+
try:
|
|
175
|
+
self._parse_header()
|
|
176
|
+
except BaseException:
|
|
177
|
+
self._lock.release()
|
|
178
|
+
raise
|
|
179
|
+
|
|
180
|
+
@staticmethod
|
|
181
|
+
def _size_of(fp) -> int:
|
|
182
|
+
try:
|
|
183
|
+
cur = fp.tell()
|
|
184
|
+
fp.seek(0, os.SEEK_END)
|
|
185
|
+
size = fp.tell()
|
|
186
|
+
fp.seek(cur)
|
|
187
|
+
return size
|
|
188
|
+
except Exception:
|
|
189
|
+
return 0
|
|
190
|
+
|
|
191
|
+
def _parse_header(self) -> None:
|
|
192
|
+
self._fp.seek(0)
|
|
193
|
+
raw = self._fp.read(_HEADER_LEN)
|
|
194
|
+
if len(raw) < _HEADER_LEN:
|
|
195
|
+
raise BinaryLogError("文件太短, 不是有效的 .plog")
|
|
196
|
+
magic, version, flags, cnt, created, index_off, _ = struct.unpack(
|
|
197
|
+
_HEADER_FMT, raw)
|
|
198
|
+
if magic != MAGIC:
|
|
199
|
+
hint = ""
|
|
200
|
+
if self._file_size > _HEADER_LEN:
|
|
201
|
+
hint = " (若文件头损坏, 可用 recover() 尝试扫描恢复记录)"
|
|
202
|
+
raise BinaryLogError("魔数不匹配, 不是 .plog 文件" + hint)
|
|
203
|
+
self.version = version
|
|
204
|
+
self.flags = flags
|
|
205
|
+
self.record_count = cnt
|
|
206
|
+
self.created_at = created
|
|
207
|
+
self.index_offset = index_off
|
|
208
|
+
self._compressed = bool(flags & _FLAG_COMPRESSED)
|
|
209
|
+
self._index: List[Tuple[int, int]] = []
|
|
210
|
+
if index_off and index_off < self._file_size:
|
|
211
|
+
self._load_index(index_off)
|
|
212
|
+
|
|
213
|
+
def _load_index(self, offset: int) -> None:
|
|
214
|
+
self._fp.seek(offset)
|
|
215
|
+
raw = self._fp.read(4)
|
|
216
|
+
if len(raw) < 4:
|
|
217
|
+
return
|
|
218
|
+
(count,) = struct.unpack("<I", raw)
|
|
219
|
+
# 防御: 索引条目数异常时不再信任索引
|
|
220
|
+
max_entries = max(1, self._file_size // 16 + 1)
|
|
221
|
+
if count > max_entries:
|
|
222
|
+
self.errors.append(
|
|
223
|
+
{"offset": offset, "reason": f"索引条目数异常({count}), 已忽略索引"})
|
|
224
|
+
self.index_offset = 0
|
|
225
|
+
return
|
|
226
|
+
for _ in range(count):
|
|
227
|
+
chunk = self._fp.read(16)
|
|
228
|
+
if len(chunk) < 16:
|
|
229
|
+
break
|
|
230
|
+
off, ts = struct.unpack("<QQ", chunk)
|
|
231
|
+
self._index.append((off, ts))
|
|
232
|
+
|
|
233
|
+
def _read_at(self, offset: int) -> Dict[str, Any]:
|
|
234
|
+
"""精确读取指定偏移的一条记录 (校验失败则抛异常)。"""
|
|
235
|
+
self._fp.seek(offset)
|
|
236
|
+
head = self._fp.read(_RECORD_HEAD_LEN)
|
|
237
|
+
if len(head) < _RECORD_HEAD_LEN:
|
|
238
|
+
raise BinaryLogError(f"记录头截断 @ {offset}")
|
|
239
|
+
length, epoch_ms, level = struct.unpack(_RECORD_HEAD_FMT, head)
|
|
240
|
+
if length > _MAX_RECORD:
|
|
241
|
+
raise BinaryLogError(f"记录长度异常 @ {offset}")
|
|
242
|
+
raw = self._fp.read(length)
|
|
243
|
+
crc_raw = self._fp.read(_CRC_LEN)
|
|
244
|
+
if len(raw) < length or len(crc_raw) < _CRC_LEN:
|
|
245
|
+
raise BinaryLogError(f"记录体截断 @ {offset}")
|
|
246
|
+
(crc,) = struct.unpack(_CRC_FMT, crc_raw)
|
|
247
|
+
if (zlib.crc32(raw) & 0xFFFFFFFF) != crc:
|
|
248
|
+
raise BinaryLogError(f"CRC32 校验失败 @ {offset}")
|
|
249
|
+
if self._compressed:
|
|
250
|
+
raw = zlib.decompress(raw)
|
|
251
|
+
data = json.loads(raw.decode("utf-8"))
|
|
252
|
+
data.setdefault("epoch_ms", epoch_ms)
|
|
253
|
+
return data
|
|
254
|
+
|
|
255
|
+
def _try_decode(self, pos: int):
|
|
256
|
+
self._fp.seek(pos)
|
|
257
|
+
head = self._fp.read(_RECORD_HEAD_LEN)
|
|
258
|
+
if len(head) < _RECORD_HEAD_LEN:
|
|
259
|
+
return None, None
|
|
260
|
+
length, epoch_ms, level = struct.unpack(_RECORD_HEAD_FMT, head)
|
|
261
|
+
if length > _MAX_RECORD or level > 100 or epoch_ms <= 0:
|
|
262
|
+
return 0, None # 头部不可信, 交由 resync
|
|
263
|
+
raw = self._fp.read(length)
|
|
264
|
+
crc_raw = self._fp.read(_CRC_LEN)
|
|
265
|
+
if len(raw) < length or len(crc_raw) < _CRC_LEN:
|
|
266
|
+
return None, None
|
|
267
|
+
(crc,) = struct.unpack(_CRC_FMT, crc_raw)
|
|
268
|
+
next_pos = pos + _RECORD_HEAD_LEN + length + _CRC_LEN
|
|
269
|
+
try:
|
|
270
|
+
if (zlib.crc32(raw) & 0xFFFFFFFF) != crc:
|
|
271
|
+
raise BinaryLogError("crc")
|
|
272
|
+
payload = zlib.decompress(raw) if self._compressed else raw
|
|
273
|
+
data = json.loads(payload.decode("utf-8"))
|
|
274
|
+
data.setdefault("epoch_ms", epoch_ms)
|
|
275
|
+
return next_pos, data
|
|
276
|
+
except Exception:
|
|
277
|
+
return next_pos, None # 体可读但内容坏, 跳过本条继续
|
|
278
|
+
|
|
279
|
+
def _resync(self, pos: int, window: Optional[int] = None) -> Optional[int]:
|
|
280
|
+
fp = self._fp
|
|
281
|
+
limit = _RESYNC_WINDOW if window is None else window
|
|
282
|
+
end = min(self._file_size, pos + limit) if limit else self._file_size
|
|
283
|
+
for cand in range(pos + 1, end):
|
|
284
|
+
fp.seek(cand)
|
|
285
|
+
head = fp.read(_RECORD_HEAD_LEN)
|
|
286
|
+
if len(head) < _RECORD_HEAD_LEN:
|
|
287
|
+
break
|
|
288
|
+
length, epoch_ms, level = struct.unpack(_RECORD_HEAD_FMT, head)
|
|
289
|
+
if length > _MAX_RECORD or level > 100 or epoch_ms <= 0:
|
|
290
|
+
continue
|
|
291
|
+
if cand + _RECORD_HEAD_LEN + length + _CRC_LEN > self._file_size:
|
|
292
|
+
continue
|
|
293
|
+
nxt, data = self._try_decode(cand)
|
|
294
|
+
if data is not None:
|
|
295
|
+
return cand
|
|
296
|
+
return None
|
|
297
|
+
|
|
298
|
+
def __iter__(self) -> Iterator[Dict[str, Any]]:
|
|
299
|
+
stop = self.index_offset or self._file_size or 0
|
|
300
|
+
pos = HEADER_SIZE
|
|
301
|
+
while pos < stop:
|
|
302
|
+
next_pos, data = self._try_decode(pos)
|
|
303
|
+
if data is not None:
|
|
304
|
+
yield data
|
|
305
|
+
if next_pos is None or next_pos <= pos:
|
|
306
|
+
break # 防御: 位置没有前进, 避免死循环
|
|
307
|
+
pos = next_pos
|
|
308
|
+
continue
|
|
309
|
+
# 坏记录处理
|
|
310
|
+
if next_pos is None:
|
|
311
|
+
# 头部不可信 -> 尝试重同步
|
|
312
|
+
if self.strict:
|
|
313
|
+
raise BinaryLogError(f"记录损坏且无法定位 @ {pos}")
|
|
314
|
+
self.errors.append({"offset": pos, "reason": "记录头损坏"})
|
|
315
|
+
sync = self._resync(pos)
|
|
316
|
+
if sync is None:
|
|
317
|
+
break
|
|
318
|
+
pos = sync
|
|
319
|
+
continue
|
|
320
|
+
else:
|
|
321
|
+
# 体损坏但长度可用 -> 跳过本条
|
|
322
|
+
if self.strict:
|
|
323
|
+
raise BinaryLogError(f"记录校验失败 @ {pos}")
|
|
324
|
+
self.errors.append({"offset": pos, "reason": "记录体校验失败, 已跳过"})
|
|
325
|
+
pos = next_pos
|
|
326
|
+
continue
|
|
327
|
+
|
|
328
|
+
def read_all(self) -> List[Dict[str, Any]]:
|
|
329
|
+
return list(self.__iter__())
|
|
330
|
+
|
|
331
|
+
def query(self, start_ms: Optional[int] = None,
|
|
332
|
+
end_ms: Optional[int] = None,
|
|
333
|
+
level_min: int = 0) -> List[Dict[str, Any]]:
|
|
334
|
+
"""按时间区间与最低级别查询; 遇到坏记录同样跳过并继续。"""
|
|
335
|
+
start_offset = self._find_start_offset(start_ms)
|
|
336
|
+
results: List[Dict[str, Any]] = []
|
|
337
|
+
stop = self.index_offset or self._file_size or 0
|
|
338
|
+
pos = max(start_offset, HEADER_SIZE)
|
|
339
|
+
while pos < stop:
|
|
340
|
+
next_pos, data = self._try_decode(pos)
|
|
341
|
+
if data is not None and (next_pos is None or next_pos <= pos):
|
|
342
|
+
break
|
|
343
|
+
if data is None:
|
|
344
|
+
if next_pos is None:
|
|
345
|
+
if self.strict:
|
|
346
|
+
raise BinaryLogError(f"记录损坏且无法定位 @ {pos}")
|
|
347
|
+
self.errors.append({"offset": pos, "reason": "记录头损坏"})
|
|
348
|
+
sync = self._resync(pos)
|
|
349
|
+
if sync is None:
|
|
350
|
+
break
|
|
351
|
+
pos = sync
|
|
352
|
+
continue
|
|
353
|
+
if self.strict:
|
|
354
|
+
raise BinaryLogError(f"记录校验失败 @ {pos}")
|
|
355
|
+
self.errors.append({"offset": pos, "reason": "记录体校验失败, 已跳过"})
|
|
356
|
+
pos = next_pos
|
|
357
|
+
continue
|
|
358
|
+
epoch_ms = int(data.get("epoch_ms", 0))
|
|
359
|
+
if end_ms is not None and epoch_ms > end_ms:
|
|
360
|
+
# 记录按时间大体递增, 超出上界可提前结束
|
|
361
|
+
break
|
|
362
|
+
if (level_ok(data, level_min)
|
|
363
|
+
and (start_ms is None or epoch_ms >= start_ms)
|
|
364
|
+
and (end_ms is None or epoch_ms <= end_ms)):
|
|
365
|
+
results.append(data)
|
|
366
|
+
pos = next_pos # type: ignore[assignment]
|
|
367
|
+
return results
|
|
368
|
+
|
|
369
|
+
def _find_start_offset(self, start_ms: Optional[int]) -> int:
|
|
370
|
+
if start_ms and self._index:
|
|
371
|
+
for off, ts in self._index:
|
|
372
|
+
if ts >= start_ms:
|
|
373
|
+
return off
|
|
374
|
+
return HEADER_SIZE
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def level_ok(data: Dict[str, Any], level_min: int) -> bool:
|
|
378
|
+
if level_min <= 0:
|
|
379
|
+
return True
|
|
380
|
+
return int(data.get("level_value", data.get("level", 20))) >= level_min
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def recover(src: str, dst: Optional[str] = None,
|
|
384
|
+
compress: bool = True) -> Dict[str, Any]:
|
|
385
|
+
"""文件头损坏时的终极恢复: 不解析头部, 从头到尾扫描可解码记录,
|
|
386
|
+
把能救回来的全部写进一个新的 .plog 文件。
|
|
387
|
+
|
|
388
|
+
返回 {'recovered': 条数, 'dst': 新文件路径}。
|
|
389
|
+
"""
|
|
390
|
+
dst = dst or (src + ".recovered.plog")
|
|
391
|
+
size = os.path.getsize(src)
|
|
392
|
+
recovered: List[Dict[str, Any]] = []
|
|
393
|
+
with open(src, "rb") as fp:
|
|
394
|
+
pos = 0
|
|
395
|
+
while pos < size:
|
|
396
|
+
fp.seek(pos)
|
|
397
|
+
head = fp.read(_RECORD_HEAD_LEN)
|
|
398
|
+
if len(head) < _RECORD_HEAD_LEN:
|
|
399
|
+
break
|
|
400
|
+
length, epoch_ms, level = struct.unpack(_RECORD_HEAD_FMT, head)
|
|
401
|
+
candidate = None
|
|
402
|
+
fits = pos + _RECORD_HEAD_LEN + length + _CRC_LEN <= size
|
|
403
|
+
if length <= _MAX_RECORD and level <= 100 and epoch_ms > 0 and fits:
|
|
404
|
+
raw = fp.read(length)
|
|
405
|
+
crc_raw = fp.read(_CRC_LEN)
|
|
406
|
+
if len(raw) == length and len(crc_raw) == _CRC_LEN:
|
|
407
|
+
(crc,) = struct.unpack(_CRC_FMT, crc_raw)
|
|
408
|
+
if (zlib.crc32(raw) & 0xFFFFFFFF) == crc:
|
|
409
|
+
try:
|
|
410
|
+
payload = (zlib.decompress(raw) if compress
|
|
411
|
+
else raw)
|
|
412
|
+
data = json.loads(payload.decode("utf-8"))
|
|
413
|
+
data.setdefault("epoch_ms", epoch_ms)
|
|
414
|
+
candidate = data
|
|
415
|
+
pos += _RECORD_HEAD_LEN + length + _CRC_LEN
|
|
416
|
+
except Exception:
|
|
417
|
+
candidate = None
|
|
418
|
+
if candidate is not None:
|
|
419
|
+
recovered.append(candidate)
|
|
420
|
+
else:
|
|
421
|
+
nxt = _scan_next(fp, pos, size, compress)
|
|
422
|
+
if nxt is None:
|
|
423
|
+
break
|
|
424
|
+
pos = nxt
|
|
425
|
+
with open(dst, "w+b") as out:
|
|
426
|
+
writer = PlogWriter.open(out, compress=compress)[0]
|
|
427
|
+
for data in recovered:
|
|
428
|
+
writer.write_record(data)
|
|
429
|
+
writer.close()
|
|
430
|
+
return {"recovered": len(recovered), "dst": dst}
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _scan_next(fp, pos: int, size: int, compress: bool) -> Optional[int]:
|
|
434
|
+
"""从 pos+1 逐字节扫描到文件末尾, 返回第一个可完整解码的位置。"""
|
|
435
|
+
for cand in range(pos + 1, min(size, pos + _RESYNC_WINDOW)):
|
|
436
|
+
fp.seek(cand)
|
|
437
|
+
head = fp.read(_RECORD_HEAD_LEN)
|
|
438
|
+
if len(head) < _RECORD_HEAD_LEN:
|
|
439
|
+
break
|
|
440
|
+
length, epoch_ms, level = struct.unpack(_RECORD_HEAD_FMT, head)
|
|
441
|
+
if length > _MAX_RECORD or level > 100 or epoch_ms <= 0:
|
|
442
|
+
continue
|
|
443
|
+
if cand + _RECORD_HEAD_LEN + length + _CRC_LEN > size:
|
|
444
|
+
continue
|
|
445
|
+
fp.seek(cand)
|
|
446
|
+
saved = fp.tell()
|
|
447
|
+
reader = PlogReader(fp, strict=False)
|
|
448
|
+
try:
|
|
449
|
+
next_pos, data = reader._try_decode(cand)
|
|
450
|
+
finally:
|
|
451
|
+
reader._lock.release()
|
|
452
|
+
if data is not None:
|
|
453
|
+
return cand
|
|
454
|
+
return None
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def inspect(path: str) -> Dict[str, Any]:
|
|
458
|
+
"""读取 .plog 文件头信息, 用于诊断。"""
|
|
459
|
+
with open(path, "rb") as fp:
|
|
460
|
+
reader = PlogReader(fp)
|
|
461
|
+
return {
|
|
462
|
+
"path": path,
|
|
463
|
+
"version": hex(reader.version),
|
|
464
|
+
"compressed": reader._compressed,
|
|
465
|
+
"record_count": reader.record_count,
|
|
466
|
+
"has_index": bool(reader.index_offset),
|
|
467
|
+
"file_size": reader._file_size,
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def verify(path: str) -> Dict[str, Any]:
|
|
472
|
+
"""完整扫描文件, 统计有效/损坏记录, 用于体检。"""
|
|
473
|
+
with open(path, "rb") as fp:
|
|
474
|
+
reader = PlogReader(fp, strict=False)
|
|
475
|
+
recs = reader.read_all()
|
|
476
|
+
return {
|
|
477
|
+
"path": path,
|
|
478
|
+
"valid_records": len(recs),
|
|
479
|
+
"corrupt_records": len(reader.errors),
|
|
480
|
+
"errors": reader.errors[:20],
|
|
481
|
+
}
|
prolog/core.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
from typing import Any, Dict, Optional, Sequence, Union
|
|
6
|
+
|
|
7
|
+
from prolog.formatters import (Formatter, HtmlFormatter, JsonFormatter,
|
|
8
|
+
JsonlFormatter, MarkdownFormatter,
|
|
9
|
+
TextFormatter, XmlFormatter, guess_formatter)
|
|
10
|
+
from prolog.handlers import (AsyncHandler, BinaryFileHandler, FileHandler,
|
|
11
|
+
Handler, NullHandler, RotatingFileHandler,
|
|
12
|
+
StreamHandler, TimedRotatingFileHandler)
|
|
13
|
+
from prolog.levels import Level, normalize_level
|
|
14
|
+
from prolog.logger import Logger
|
|
15
|
+
|
|
16
|
+
_FORMATTERS = {
|
|
17
|
+
"text": TextFormatter, "txt": TextFormatter,
|
|
18
|
+
"json": JsonFormatter, "jsonl": JsonlFormatter,
|
|
19
|
+
"xml": XmlFormatter, "markdown": MarkdownFormatter, "md": MarkdownFormatter,
|
|
20
|
+
"html": HtmlFormatter,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Prolog:
|
|
25
|
+
|
|
26
|
+
def __init__(self, name: str = "root", level: object = Level.INFO,
|
|
27
|
+
console: bool = True, console_color: Optional[bool] = None,
|
|
28
|
+
files: Optional[Sequence[Dict[str, Any]]] = None,
|
|
29
|
+
async_write: bool = False):
|
|
30
|
+
self.name = name
|
|
31
|
+
self.root = Logger(name, level=level)
|
|
32
|
+
self._loggers: Dict[str, Logger] = {name: self.root}
|
|
33
|
+
if console:
|
|
34
|
+
self.root.add_handler(StreamHandler(color=console_color))
|
|
35
|
+
if files:
|
|
36
|
+
for cfg in files:
|
|
37
|
+
self.root.add_handler(self._build_file_handler(cfg, async_write))
|
|
38
|
+
|
|
39
|
+
# -- 构造辅助 ---------------------------------------------------------
|
|
40
|
+
@staticmethod
|
|
41
|
+
def _build_file_handler(cfg: Dict[str, Any], async_write: bool) -> Handler:
|
|
42
|
+
path = cfg["path"]
|
|
43
|
+
fmt_name = cfg.get("format")
|
|
44
|
+
if fmt_name:
|
|
45
|
+
fmt_cls = _FORMATTERS.get(fmt_name.lower())
|
|
46
|
+
formatter = fmt_cls() if fmt_cls else TextFormatter()
|
|
47
|
+
else:
|
|
48
|
+
formatter = guess_formatter(path)
|
|
49
|
+
kind = cfg.get("type", "auto")
|
|
50
|
+
level = cfg.get("level")
|
|
51
|
+
if path.endswith(".plog") or kind == "binary":
|
|
52
|
+
handler: Handler = BinaryFileHandler(path, level=level,
|
|
53
|
+
compress=cfg.get("compress", True))
|
|
54
|
+
elif kind == "rotate" or cfg.get("max_bytes"):
|
|
55
|
+
handler = RotatingFileHandler(
|
|
56
|
+
path, level=level, formatter=formatter,
|
|
57
|
+
max_bytes=cfg.get("max_bytes", 10 * 1024 * 1024),
|
|
58
|
+
backup_count=cfg.get("backup_count", 5),
|
|
59
|
+
compress=cfg.get("compress", True))
|
|
60
|
+
elif kind == "time" or cfg.get("when"):
|
|
61
|
+
handler = TimedRotatingFileHandler(
|
|
62
|
+
path, level=level, formatter=formatter,
|
|
63
|
+
when=cfg.get("when", "D"),
|
|
64
|
+
interval=cfg.get("interval", 1),
|
|
65
|
+
backup_count=cfg.get("backup_count", 7))
|
|
66
|
+
else:
|
|
67
|
+
handler = FileHandler(path, level=level, formatter=formatter)
|
|
68
|
+
if async_write or cfg.get("async"):
|
|
69
|
+
handler = AsyncHandler(handler)
|
|
70
|
+
return handler
|
|
71
|
+
|
|
72
|
+
# -- 获取子 Logger ----------------------------------------------------
|
|
73
|
+
def get_logger(self, name: str, level: Optional[object] = None) -> Logger:
|
|
74
|
+
if name in self._loggers:
|
|
75
|
+
return self._loggers[name]
|
|
76
|
+
child = Logger(name, level=level, parent=self.root)
|
|
77
|
+
self._loggers[name] = child
|
|
78
|
+
return child
|
|
79
|
+
|
|
80
|
+
# -- 快捷方法 ----------------------------------------
|
|
81
|
+
def trace(self, msg: str, *a: Any, **kw: Any) -> None:
|
|
82
|
+
self.root.trace(msg, *a, **kw)
|
|
83
|
+
|
|
84
|
+
def debug(self, msg: str, *a: Any, **kw: Any) -> None:
|
|
85
|
+
self.root.debug(msg, *a, **kw)
|
|
86
|
+
|
|
87
|
+
def info(self, msg: str, *a: Any, **kw: Any) -> None:
|
|
88
|
+
self.root.info(msg, *a, **kw)
|
|
89
|
+
|
|
90
|
+
def success(self, msg: str, *a: Any, **kw: Any) -> None:
|
|
91
|
+
self.root.success(msg, *a, **kw)
|
|
92
|
+
|
|
93
|
+
def warning(self, msg: str, *a: Any, **kw: Any) -> None:
|
|
94
|
+
self.root.warning(msg, *a, **kw)
|
|
95
|
+
|
|
96
|
+
def error(self, msg: str, *a: Any, **kw: Any) -> None:
|
|
97
|
+
self.root.error(msg, *a, **kw)
|
|
98
|
+
|
|
99
|
+
def critical(self, msg: str, *a: Any, **kw: Any) -> None:
|
|
100
|
+
self.root.critical(msg, *a, **kw)
|
|
101
|
+
|
|
102
|
+
def exception(self, msg: str, exc: BaseException, **kw: Any) -> None:
|
|
103
|
+
self.root.exception(msg, exc, **kw)
|
|
104
|
+
|
|
105
|
+
def timer(self, message: str, level: object = Level.INFO, **kw: Any):
|
|
106
|
+
return self.root.timer(message, level=level, **kw)
|
|
107
|
+
|
|
108
|
+
def flush(self) -> None:
|
|
109
|
+
self.root.flush()
|
|
110
|
+
|
|
111
|
+
def shutdown(self) -> None:
|
|
112
|
+
for logger in self._loggers.values():
|
|
113
|
+
for handler in logger.handlers:
|
|
114
|
+
try:
|
|
115
|
+
handler.close()
|
|
116
|
+
except Exception:
|
|
117
|
+
pass
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
__all__ = ["Prolog"]
|