-
-
Notifications
You must be signed in to change notification settings - Fork 450
Expand file tree
/
Copy pathlogging_utils.py
More file actions
316 lines (261 loc) · 11 KB
/
Copy pathlogging_utils.py
File metadata and controls
316 lines (261 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
"""
Pretty, column-aligned, color-aware logging for MasterHttpRelayVPN.
Zero extra dependencies. On Windows, ANSI color support is enabled via
the Console API. Colors are disabled automatically when:
- The output stream is not a TTY (e.g. piped to a file)
- The NO_COLOR environment variable is set
- DFT_NO_COLOR=1 is set
"""
from __future__ import annotations
import logging
import os
import sys
import time
# ─── ANSI palette ──────────────────────────────────────────────────────────
RESET = "\x1b[0m"
BOLD = "\x1b[1m"
DIM = "\x1b[2m"
ITALIC = "\x1b[3m"
# 8-bit / truecolor friendly foreground codes
FG_GRAY = "\x1b[38;5;245m"
FG_BLUE = "\x1b[38;5;39m"
FG_CYAN = "\x1b[38;5;45m"
FG_GREEN = "\x1b[38;5;42m"
FG_YELLOW = "\x1b[38;5;214m"
FG_RED = "\x1b[38;5;203m"
FG_MAGENTA = "\x1b[38;5;177m"
FG_PURPLE = "\x1b[38;5;141m"
FG_TEAL = "\x1b[38;5;80m"
FG_ORANGE = "\x1b[38;5;208m"
LEVEL_STYLE = {
"DEBUG": f"{DIM}{FG_GRAY}",
"INFO": f"{FG_GREEN}",
"WARNING": f"{BOLD}{FG_YELLOW}",
"ERROR": f"{BOLD}{FG_RED}",
"CRITICAL": f"{BOLD}{FG_MAGENTA}",
}
LEVEL_GLYPH = {
"DEBUG": "·",
"INFO": "•",
"WARNING": "!",
"ERROR": "✕",
"CRITICAL": "✕",
}
LEVEL_LABEL = {
"DEBUG": "DEBUG",
"INFO": "INFO ",
"WARNING": "WARN ",
"ERROR": "ERROR",
"CRITICAL": "CRIT ",
}
# Special spotlight line for execution usage updates.
EXEC_USAGE_PREFIX = "Apps Script executions used so far:"
# Spotlight line for the CA certificate LAN download URL.
CA_DOWNLOAD_PREFIX = "CA certificate download"
# Stable per-component color (keeps log scanning easy).
COMPONENT_COLORS = {
"Main": FG_CYAN,
"Proxy": FG_BLUE,
"Fronter": FG_PURPLE,
"H2": FG_TEAL,
"MITM": FG_ORANGE,
"Cert": FG_MAGENTA,
}
# ─── color support detection ───────────────────────────────────────────────
def _supports_color(stream) -> bool:
if os.environ.get("NO_COLOR"):
return False
if os.environ.get("DFT_NO_COLOR") == "1":
return False
if os.environ.get("FORCE_COLOR") or os.environ.get("DFT_FORCE_COLOR"):
return True
if not hasattr(stream, "isatty") or not stream.isatty():
return False
if sys.platform != "win32":
return True
# Try to enable ANSI on Windows 10+ consoles.
try:
import ctypes
kernel32 = ctypes.windll.kernel32
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
# -11 = STD_OUTPUT_HANDLE
handle = kernel32.GetStdHandle(-11)
mode = ctypes.c_ulong()
if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
return False
if kernel32.SetConsoleMode(
handle, mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING
):
return True
except Exception:
return False
return False
# ─── formatter ─────────────────────────────────────────────────────────────
class PrettyFormatter(logging.Formatter):
"""Column-aligned formatter with optional ANSI colors."""
COMPONENT_WIDTH = 8
def __init__(self, *, use_color: bool):
super().__init__()
self.use_color = use_color
self._start = time.time()
# -- helpers ------------------------------------------------------------
def _c(self, code: str) -> str:
return code if self.use_color else ""
def _fmt_time(self, record: logging.LogRecord) -> str:
t = time.localtime(record.created)
ms = int((record.created - int(record.created)) * 1000)
return f"{time.strftime('%H:%M:%S', t)}"
def _fmt_level(self, levelname: str) -> str:
label = LEVEL_LABEL.get(levelname, levelname[:5].ljust(5))
glyph = LEVEL_GLYPH.get(levelname, "·")
style = LEVEL_STYLE.get(levelname, "")
if self.use_color:
return f"{style}{glyph} {label}{RESET}"
return f"{glyph} {label}"
def _fmt_component(self, name: str) -> str:
label = name[: self.COMPONENT_WIDTH].ljust(self.COMPONENT_WIDTH)
if not self.use_color:
return f"[{label}]"
color = COMPONENT_COLORS.get(name, FG_GRAY)
return f"{DIM}[{RESET}{color}{label}{RESET}{DIM}]{RESET}"
def format(self, record: logging.LogRecord) -> str:
# Pre-render message (honors %-args and {}-args).
try:
message = record.getMessage()
except Exception:
message = record.msg
highlight_exec_usage = (
record.name == "Fronter"
and isinstance(message, str)
and message.startswith(EXEC_USAGE_PREFIX)
)
highlight_ca_download = (
isinstance(message, str)
and message.startswith(CA_DOWNLOAD_PREFIX)
)
if highlight_ca_download:
plain_time = self._fmt_time(record)
plain_level = f"{LEVEL_GLYPH.get(record.levelname, '·')} {LEVEL_LABEL.get(record.levelname, record.levelname[:5].ljust(5))}"
plain_comp = f"[{record.name[: self.COMPONENT_WIDTH].ljust(self.COMPONENT_WIDTH)}]"
line = f"{plain_time} {plain_level} {plain_comp} {message}"
if self.use_color:
line = f"{BOLD}{FG_GREEN}{line}{RESET}"
elif highlight_exec_usage:
# Force a single vivid color for the entire line so this metric pops.
plain_time = self._fmt_time(record)
plain_level = f"{LEVEL_GLYPH.get(record.levelname, '·')} {LEVEL_LABEL.get(record.levelname, record.levelname[:5].ljust(5))}"
plain_comp = f"[{record.name[: self.COMPONENT_WIDTH].ljust(self.COMPONENT_WIDTH)}]"
line = f"{plain_time} {plain_level} {plain_comp} {message}"
if self.use_color:
line = f"{BOLD}{FG_CYAN}{line}{RESET}"
else:
time_part = self._fmt_time(record)
level_part = self._fmt_level(record.levelname)
comp_part = self._fmt_component(record.name)
if self.use_color:
time_part = f"{DIM}{FG_GRAY}{time_part}{RESET}"
line = f"{time_part} {level_part} {comp_part} {message}"
# Exception tracebacks: render dimmed below the main line.
if record.exc_info:
tb = self.formatException(record.exc_info)
if self.use_color:
tb = f"{DIM}{FG_GRAY}{tb}{RESET}"
line = f"{line}\n{tb}"
if record.stack_info:
si = record.stack_info
if self.use_color:
si = f"{DIM}{FG_GRAY}{si}{RESET}"
line = f"{line}\n{si}"
return line
# ─── public API ────────────────────────────────────────────────────────────
def configure(level: str = "INFO", *, stream=None) -> None:
"""Install the pretty formatter on the root logger.
Safe to call multiple times; replaces prior handlers set up by this
module and leaves unrelated handlers alone (for tests / embedding).
"""
stream = stream or sys.stderr
use_color = _supports_color(stream)
handler = logging.StreamHandler(stream)
handler.setFormatter(PrettyFormatter(use_color=use_color))
handler.set_name("mhrvpn.pretty")
root = logging.getLogger()
root.setLevel(getattr(logging, level.upper(), logging.INFO))
# Remove previous pretty handler(s) we installed.
for h in list(root.handlers):
if getattr(h, "name", "") == "mhrvpn.pretty":
root.removeHandler(h)
root.addHandler(handler)
# Suppress cosmetic asyncio warning spam:
# "returning true from eof_received() has no effect when using ssl"
# It originates in Python's own StreamReaderProtocol when we wrap a
# stream in TLS via start_tls(); there's nothing actionable to do.
_install_asyncio_noise_filter()
# Quiet very chatty third-party loggers even when the root logger is set
# to DEBUG: we only care about our own component DEBUG output. hpack
# emits one log line per header field, asyncio emits raw selector spam.
for noisy in (
"hpack",
"hpack.hpack",
"hpack.table",
"h2",
"h2.connection",
"asyncio",
"urllib3",
"chardet",
):
logging.getLogger(noisy).setLevel(logging.INFO)
class _AsyncioNoiseFilter(logging.Filter):
_SUPPRESSED = (
"returning true from eof_received() has no effect when using ssl",
)
def filter(self, record: logging.LogRecord) -> bool: # noqa: D401
try:
msg = record.getMessage()
except Exception:
return True
return not any(s in msg for s in self._SUPPRESSED)
def _install_asyncio_noise_filter() -> None:
f = _AsyncioNoiseFilter()
aio = logging.getLogger("asyncio")
# Don't stack duplicates on repeat configure() calls.
for existing in list(aio.filters):
if isinstance(existing, _AsyncioNoiseFilter):
aio.removeFilter(existing)
aio.addFilter(f)
def print_banner(version: str, *, stream=None) -> None:
"""Print an ASCII startup banner with color fallbacks."""
stream = stream or sys.stderr
color = _supports_color(stream)
def c(code: str) -> str:
return code if color else ""
art = [
" __ __ _ ____ _____ _____ ____ ",
"| \\/ | / \\ / ___|_ _| ____| _ \\ ",
"| |\\/| | / _ \\ \\___ \\ | | | _| | |_) |",
"| | | |/ ___ \\ ___) || | | |___| _ < ",
"|_| |_/_/ \\_\\____/ |_| |_____|_| \\_\\",
" _ _ _____ _____ ____ ____ _____ _ _ __ __",
" | | | |_ _|_ _| _ \\ | _ \\| ____| | / \\\\ \\ / /",
" | |_| | | | | | | |_) | | |_) | _| | | / _ \\\\ V / ",
" | _ | | | | | | __/ | _ <| |___| |___ / ___ \\| | ",
" |_| |_| |_| |_| |_| |_| \\_\\_____|_____/_/ \\_\\_| ",
]
version_line = f"Version {version}"
link = "https://github.com/masterking32/MasterHttpRelayVPN"
width = max(max(len(line) for line in art), len(version_line), len(link))
rule = "=" * width
if color:
print(f"{DIM}{FG_GRAY}{rule}{RESET}", file=stream)
for line in art:
print(f"{BOLD}{FG_CYAN}{line.center(width)}{RESET}", file=stream)
print(f"{FG_GRAY}{version_line.center(width)}{RESET}", file=stream)
print(f"{FG_TEAL}{link.center(width)}{RESET}", file=stream)
print(f"{DIM}{FG_GRAY}{rule}{RESET}", file=stream)
else:
print(rule, file=stream)
for line in art:
print(line.center(width), file=stream)
print(version_line.center(width), file=stream)
print(link.center(width), file=stream)
print(rule, file=stream)
stream.flush()