返回 last30days-skill
log.py
1 """Shared logging utilities for last30days skill."""
2
3 import os
4 import sys
5
6
7 def _sanitize_for_stream(text: str, stream) -> str:
8 """Pre-sanitize text for streams with an explicit narrow encoding.
9
10 Buffered ``io.TextIOWrapper`` streams (e.g. non-TTY pipes on Windows cp1252
11 or POSIX ASCII locales) may defer encoding until ``flush()``, so sanitizing
12 before ``write()`` prevents poisoning the stream's pending text buffer.
13 """
14 encoding = getattr(stream, "encoding", None)
15 if not isinstance(encoding, str) or not encoding:
16 return text
17 try:
18 text.encode(encoding)
19 return text
20 except UnicodeEncodeError:
21 return text.encode(encoding, errors="replace").decode(encoding, errors="replace")
22 except LookupError:
23 return text.encode("ascii", errors="replace").decode("ascii")
24
25
26 def safe_stderr_write(text: str, stream=None, *, flush: bool = True) -> None:
27 """Write text to stderr without crashing on narrow encodings or broken pipes."""
28 target = sys.stderr if stream is None else stream
29 if target is None:
30 return
31 sanitized = _sanitize_for_stream(text, target)
32 try:
33 target.write(sanitized)
34 except UnicodeEncodeError:
35 try:
36 target.write(text.encode("ascii", errors="replace").decode("ascii"))
37 except (UnicodeEncodeError, BrokenPipeError, OSError):
38 return
39 except (BrokenPipeError, OSError):
40 return
41 if flush:
42 try:
43 target.flush()
44 except (UnicodeEncodeError, BrokenPipeError, OSError):
45 pass
46
47
48 def is_debug() -> bool:
49 val = os.environ.get("LAST30DAYS_DEBUG", "")
50 return val.lower() in ("1", "true", "yes", "on")
51
52
53 def debug(msg: str) -> None:
54 """Log debug message to stderr (only when LAST30DAYS_DEBUG is set)."""
55 if is_debug():
56 safe_stderr_write(f"[DEBUG] {msg}\n")
57
58
59 def source_log(prefix: str, msg: str, *, tty_only: bool = True) -> None:
60 """Log a source module message to stderr.
61
62 Args:
63 prefix: Source label (e.g. "Reddit", "Bird").
64 msg: Message text.
65 tty_only: If True, only log when stderr is a TTY (avoids cluttering
66 non-interactive output like Claude Code).
67
68 CONVENTION: source modules under `lib/` must call this with
69 `tty_only=False`. The default exists to keep ad-hoc callers quiet, but
70 a source module's logs are observability — silently dropping them under
71 Claude Code, Codex, or CI hides both failures and success signals from
72 the user and the synthesis LLM. The convention is enforced by
73 `tests/test_source_log_visibility.py`.
74 """
75 if tty_only:
76 try:
77 if sys.stderr is None or not sys.stderr.isatty():
78 return
79 except OSError:
80 return
81 safe_stderr_write(f"[{prefix}] {msg}\n")
82
82 lines PYTHON