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/formatters.py ADDED
@@ -0,0 +1,218 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import io
5
+ import json
6
+ from abc import ABC, abstractmethod
7
+ from typing import Dict, List, Optional
8
+
9
+ from prolog.levels import Level
10
+ from prolog.record import LogRecord
11
+
12
+ # ----------------------------------------------------------------------
13
+ # ANSI 颜色
14
+ # ----------------------------------------------------------------------
15
+ _RESET = "\033[0m"
16
+ _COLORS = {
17
+ Level.TRACE: "\033[90m", # 灰
18
+ Level.DEBUG: "\033[36m", # 青
19
+ Level.INFO: "\033[32m", # 绿
20
+ Level.SUCCESS: "\033[1;32m", # 亮绿
21
+ Level.WARNING: "\033[33m", # 黄
22
+ Level.ERROR: "\033[31m", # 红
23
+ Level.CRITICAL: "\033[1;41m", # 红底
24
+ }
25
+
26
+
27
+ def colorize(text: str, level: Level, enabled: bool) -> str:
28
+ if not enabled:
29
+ return text
30
+ return f"{_COLORS.get(level, '')}{text}{_RESET}"
31
+
32
+
33
+ class Formatter(ABC):
34
+ """格式化器基类。"""
35
+
36
+ @abstractmethod
37
+ def format(self, record: LogRecord) -> str:
38
+ ...
39
+
40
+ def header(self) -> Optional[str]: # noqa: D401 - 文件头, 可为空
41
+ return None
42
+
43
+ def footer(self) -> Optional[str]:
44
+ return None
45
+
46
+
47
+ class TextFormatter(Formatter):
48
+ """人类可读的纯文本格式 (TXT)。"""
49
+
50
+ def __init__(self, fmt: str = "[{time}] [{level:<8}] {name} | {message}",
51
+ datefmt: str = "%Y-%m-%d %H:%M:%S", color: bool = False,
52
+ render_exc: bool = True):
53
+ self.fmt = fmt
54
+ self.datefmt = datefmt
55
+ self.color = color
56
+ self.render_exc = render_exc
57
+
58
+ def format(self, record: LogRecord) -> str:
59
+ timestamp = record.timestamp.astimezone().strftime(self.datefmt)
60
+ level_txt = record.level_name
61
+ if self.color:
62
+ level_txt = colorize(level_txt, record.level, True)
63
+ line = self.fmt.format(
64
+ time=timestamp,
65
+ level=level_txt,
66
+ name=record.logger_name,
67
+ message=record.message,
68
+ thread=record.thread_name,
69
+ process=record.process_id,
70
+ host=record.hostname,
71
+ )
72
+ if record.exc_info and self.render_exc:
73
+ line = f"{line}\n{record.exc_info}"
74
+ if record.extra:
75
+ extra_txt = " ".join(f"{k}={v!r}" for k, v in record.extra.items())
76
+ line = f"{line} {{{extra_txt}}}"
77
+ return line
78
+
79
+
80
+ class JsonFormatter(Formatter):
81
+ def __init__(self, ensure_ascii: bool = False, indent: Optional[int] = None):
82
+ self.ensure_ascii = ensure_ascii
83
+ self.indent = indent
84
+
85
+ def format(self, record: LogRecord) -> str:
86
+ return json.dumps(record.to_dict(), ensure_ascii=self.ensure_ascii,
87
+ indent=self.indent, default=str)
88
+
89
+
90
+ class JsonlFormatter(Formatter):
91
+ """JSON Lines: 每行一个 JSON 对象, 适合流式与大数据分析。"""
92
+
93
+ def format(self, record: LogRecord) -> str:
94
+ return json.dumps(record.to_dict(), ensure_ascii=False, default=str)
95
+
96
+
97
+ class CsvFormatter(Formatter):
98
+ FIELDS: List[str] = ["id", "time", "level", "logger", "message",
99
+ "thread", "process", "host", "extra", "exc_info"]
100
+
101
+ def __init__(self, delimiter: str = ",", fields: Optional[List[str]] = None):
102
+ self.delimiter = delimiter
103
+ self.fields = fields or self.FIELDS
104
+
105
+ def header(self) -> str:
106
+ return self.delimiter.join(self.fields)
107
+
108
+ def format(self, record: LogRecord) -> str:
109
+ data = record.to_dict()
110
+ buf = io.StringIO()
111
+ writer = csv.DictWriter(buf, fieldnames=self.fields,
112
+ delimiter=self.delimiter, extrasaction="ignore")
113
+ row = {k: (json.dumps(v, ensure_ascii=False, default=str)
114
+ if isinstance(v, (dict, list)) else v)
115
+ for k, v in data.items()}
116
+ writer.writerow(row)
117
+ return buf.getvalue().rstrip("\r\n")
118
+
119
+
120
+ class XmlFormatter(Formatter):
121
+ def header(self) -> str:
122
+ return '<?xml version="1.0" encoding="UTF-8"?>\n<log>'
123
+
124
+ def footer(self) -> str:
125
+ return "</log>"
126
+
127
+ def format(self, record: LogRecord) -> str:
128
+ data = record.to_dict()
129
+ parts = [" <record>"]
130
+ for key, value in data.items():
131
+ if value is None:
132
+ value = ""
133
+ parts.append(f" <{key}>{_escape(str(value))}</{key}>")
134
+ parts.append(" </record>")
135
+ return "\n".join(parts)
136
+
137
+
138
+ class MarkdownFormatter(Formatter):
139
+ def header(self) -> str:
140
+ # 文件开头写一次标题
141
+ return "# 运行日志\n"
142
+
143
+ def format(self, record: LogRecord) -> str:
144
+ # 每行日志:级别 + 时间 + logger名 + 消息(无图标)
145
+ lines = [
146
+ f"### {record.level_name} - {record.local_time}",
147
+ f"**Logger**: `{record.logger_name}` ",
148
+ f"**Message**: {record.message} ",
149
+ ]
150
+ # 有自定义字段就追加 Extra 段
151
+ if record.extra:
152
+ lines.append("**Extra**:")
153
+ for k, v in record.extra.items():
154
+ lines.append(f"- `{k}`: {v}")
155
+ # 有异常就追加堆栈代码块
156
+ if record.exc_info:
157
+ lines.append(f"\n```\n{record.exc_info}\n```")
158
+ return "\n".join(lines)
159
+
160
+ class HtmlFormatter(Formatter):
161
+ """输出单条 HTML 片段,由 RotatingFileHandler 决定是否补全页面。"""
162
+
163
+ _ROW = ('<tr class="{cls}"><td>{time}</td><td>{level}</td>'
164
+ '<td>{name}</td><td>{msg}</td></tr>')
165
+
166
+ def header(self) -> str:
167
+ return (
168
+ "<!DOCTYPE html>\n<html><head><meta charset='utf-8'>"
169
+ "<title>Prolog Log</title><style>"
170
+ "body{font-family:Consolas,monospace;background:#1e1e1e;color:#ddd}"
171
+ "table{border-collapse:collapse;width:100%}"
172
+ "td,th{border:1px solid #444;padding:4px 8px;text-align:left}"
173
+ "th{background:#333}"
174
+ ".DEBUG{color:#4dc4c4}.INFO{color:#5dd15d}.SUCCESS{color:#7CFC00}"
175
+ ".WARNING{color:#e0c341}.ERROR{color:#e06c6c}"
176
+ ".CRITICAL{background:#a11;color:#fff}"
177
+ "</style></head><body><table><thead><tr>"
178
+ "<th>时间</th><th>级别</th><th>Logger</th><th>消息</th>"
179
+ "</tr></thead><tbody>"
180
+ )
181
+
182
+ def footer(self) -> str:
183
+ return "</tbody></table></body></html>"
184
+
185
+ def format(self, record: LogRecord) -> str:
186
+ return self._ROW.format(
187
+ cls=record.level_name,
188
+ time=record.local_time,
189
+ level=record.level_name,
190
+ name=_escape(record.logger_name),
191
+ msg=_escape(record.message),
192
+ )
193
+
194
+
195
+ def _escape(text: str) -> str:
196
+ return (text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
197
+ .replace('"', "&quot;"))
198
+
199
+
200
+ #: 扩展名 -> Formatter 的便捷映射
201
+ FORMATTER_MAP = {
202
+ "txt": TextFormatter,
203
+ "log": TextFormatter,
204
+ "json": JsonFormatter,
205
+ "jsonl": JsonlFormatter,
206
+ "csv": CsvFormatter,
207
+ "xml": XmlFormatter,
208
+ "md": MarkdownFormatter,
209
+ "html": HtmlFormatter,
210
+ "htm": HtmlFormatter,
211
+ }
212
+
213
+
214
+ def guess_formatter(path: str) -> Formatter:
215
+ """按文件扩展名自动选择格式化器。"""
216
+ ext = path.rsplit(".", 1)[-1].lower() if "." in path else "txt"
217
+ cls = FORMATTER_MAP.get(ext, TextFormatter)
218
+ return cls()