tracekit-sdk 0.1.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.
- tracekit/__init__.py +161 -0
- tracekit/cli.py +144 -0
- tracekit/client.py +194 -0
- tracekit/config.py +47 -0
- tracekit/event.py +190 -0
- tracekit/filters.py +162 -0
- tracekit/hooks.py +150 -0
- tracekit/integrations/__init__.py +5 -0
- tracekit/integrations/logging.py +75 -0
- tracekit/py.typed +1 -0
- tracekit/scope.py +136 -0
- tracekit/sinks.py +205 -0
- tracekit/tracing.py +168 -0
- tracekit/transport.py +155 -0
- tracekit/viewer.py +200 -0
- tracekit_sdk-0.1.0.dist-info/METADATA +266 -0
- tracekit_sdk-0.1.0.dist-info/RECORD +20 -0
- tracekit_sdk-0.1.0.dist-info/WHEEL +4 -0
- tracekit_sdk-0.1.0.dist-info/entry_points.txt +2 -0
- tracekit_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
tracekit/__init__.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""
|
|
2
|
+
tracekit — public API surface (PRD §1.5).
|
|
3
|
+
|
|
4
|
+
Only the symbols listed here are part of the public contract.
|
|
5
|
+
Internals live in sub-modules; this file stays thin.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import sys
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from tracekit.client import Client, _set_client, get_client
|
|
15
|
+
from tracekit.config import Config
|
|
16
|
+
from tracekit.hooks import install_asyncio_hook, install_hooks
|
|
17
|
+
from tracekit.integrations.logging import TraceKitHandler
|
|
18
|
+
from tracekit.scope import add_breadcrumb, set_tag, set_user
|
|
19
|
+
from tracekit.tracing import span, trace
|
|
20
|
+
|
|
21
|
+
__version__: str = "0.1.0"
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"__version__",
|
|
25
|
+
"init",
|
|
26
|
+
"capture_exception",
|
|
27
|
+
"capture_message",
|
|
28
|
+
"install_asyncio_hook",
|
|
29
|
+
"trace",
|
|
30
|
+
"span",
|
|
31
|
+
"set_user",
|
|
32
|
+
"set_tag",
|
|
33
|
+
"add_breadcrumb",
|
|
34
|
+
"flush",
|
|
35
|
+
"shutdown",
|
|
36
|
+
"TraceKitHandler",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# ---------------------------------------------------------------------------
|
|
41
|
+
# init()
|
|
42
|
+
# ---------------------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def init(
|
|
46
|
+
output: str = "console",
|
|
47
|
+
*,
|
|
48
|
+
environment: str = "production",
|
|
49
|
+
release: str | None = None,
|
|
50
|
+
sample_rate: float = 1.0,
|
|
51
|
+
ignore_errors: list[type[BaseException] | str] | None = None,
|
|
52
|
+
before_send: Callable[[dict[str, Any]], dict[str, Any] | None] | None = None,
|
|
53
|
+
debug: bool = False,
|
|
54
|
+
) -> None:
|
|
55
|
+
"""
|
|
56
|
+
Configure the SDK and install exception hooks.
|
|
57
|
+
|
|
58
|
+
Call once at application startup. Calling again replaces the active client;
|
|
59
|
+
the old client's background worker is shut down gracefully first so no
|
|
60
|
+
events are lost.
|
|
61
|
+
After calling init(), unhandled exceptions in the main thread and in
|
|
62
|
+
worker threads are captured automatically. For asyncio, also call
|
|
63
|
+
tracekit.install_asyncio_hook(loop) once a loop is available.
|
|
64
|
+
"""
|
|
65
|
+
try:
|
|
66
|
+
config = Config(
|
|
67
|
+
output=output,
|
|
68
|
+
environment=environment,
|
|
69
|
+
release=release,
|
|
70
|
+
sample_rate=sample_rate,
|
|
71
|
+
ignore_errors=ignore_errors if ignore_errors is not None else [],
|
|
72
|
+
before_send=before_send,
|
|
73
|
+
debug=debug,
|
|
74
|
+
)
|
|
75
|
+
# Shut down the previous client's transport before replacing it.
|
|
76
|
+
old = get_client()
|
|
77
|
+
if old is not None:
|
|
78
|
+
old.shutdown()
|
|
79
|
+
_set_client(Client(config))
|
|
80
|
+
install_hooks()
|
|
81
|
+
except Exception as e:
|
|
82
|
+
# init() must never crash the host application.
|
|
83
|
+
print(f"[TraceKit] init() failed: {e}", file=sys.stderr)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# ---------------------------------------------------------------------------
|
|
87
|
+
# capture_exception()
|
|
88
|
+
# ---------------------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def capture_exception(exc: BaseException | None = None) -> None:
|
|
92
|
+
"""
|
|
93
|
+
Manually report an exception.
|
|
94
|
+
|
|
95
|
+
If exc is None and called from inside an except block, captures the
|
|
96
|
+
current exception via sys.exc_info(). No-op when init() has not been
|
|
97
|
+
called or there is no active exception to report.
|
|
98
|
+
"""
|
|
99
|
+
try:
|
|
100
|
+
client = get_client()
|
|
101
|
+
if client is None:
|
|
102
|
+
return
|
|
103
|
+
client.capture_exception(exc)
|
|
104
|
+
except Exception:
|
|
105
|
+
pass # public entry point: must never raise
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# ---------------------------------------------------------------------------
|
|
109
|
+
# capture_message()
|
|
110
|
+
# ---------------------------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def capture_message(text: str, level: str = "info") -> None:
|
|
114
|
+
"""
|
|
115
|
+
Report a free-form message event.
|
|
116
|
+
|
|
117
|
+
level must be one of "debug", "info", "warning", "error".
|
|
118
|
+
No-op when init() has not been called.
|
|
119
|
+
"""
|
|
120
|
+
try:
|
|
121
|
+
client = get_client()
|
|
122
|
+
if client is None:
|
|
123
|
+
return
|
|
124
|
+
client.capture_message(text, level)
|
|
125
|
+
except Exception:
|
|
126
|
+
pass # public entry point: must never raise
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# ---------------------------------------------------------------------------
|
|
130
|
+
# flush() / shutdown()
|
|
131
|
+
# ---------------------------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def flush(timeout: float = 2.0) -> None:
|
|
135
|
+
"""
|
|
136
|
+
Block until all queued events are delivered to the sink (or timeout expires).
|
|
137
|
+
|
|
138
|
+
Safe to call before init() — it is a no-op in that case.
|
|
139
|
+
Use this in scripts and tests to ensure events land before the process exits.
|
|
140
|
+
"""
|
|
141
|
+
try:
|
|
142
|
+
client = get_client()
|
|
143
|
+
if client is not None:
|
|
144
|
+
client.flush(timeout)
|
|
145
|
+
except Exception:
|
|
146
|
+
pass # public entry point: must never raise
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def shutdown() -> None:
|
|
150
|
+
"""
|
|
151
|
+
Flush all pending events and stop the background worker thread.
|
|
152
|
+
|
|
153
|
+
After this call the SDK is effectively disabled until init() is called again.
|
|
154
|
+
Safe to call before init() or multiple times — it is idempotent.
|
|
155
|
+
"""
|
|
156
|
+
try:
|
|
157
|
+
client = get_client()
|
|
158
|
+
if client is not None:
|
|
159
|
+
client.shutdown()
|
|
160
|
+
except Exception:
|
|
161
|
+
pass # public entry point: must never raise
|
tracekit/cli.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""
|
|
2
|
+
cli.py — Entry point for `tracekit tail` and `tracekit serve` sub-commands.
|
|
3
|
+
|
|
4
|
+
Uses only argparse and the stdlib; no third-party CLI framework.
|
|
5
|
+
`tracekit tail` is implemented here (Phase 5).
|
|
6
|
+
`tracekit serve` is implemented here (Phase 6).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main() -> None:
|
|
18
|
+
"""Dispatch to the correct sub-command."""
|
|
19
|
+
parser = argparse.ArgumentParser(
|
|
20
|
+
prog="tracekit",
|
|
21
|
+
description="TraceKit observability CLI",
|
|
22
|
+
)
|
|
23
|
+
sub = parser.add_subparsers(dest="command", metavar="COMMAND")
|
|
24
|
+
|
|
25
|
+
# -- tail ----------------------------------------------------------------
|
|
26
|
+
tail_p = sub.add_parser(
|
|
27
|
+
"tail",
|
|
28
|
+
help="Follow a JSONL event file and pretty-print new events in real time.",
|
|
29
|
+
)
|
|
30
|
+
tail_p.add_argument("file", help="Path to the .jsonl event file to watch.")
|
|
31
|
+
|
|
32
|
+
# -- serve ---------------------------------------------------------------
|
|
33
|
+
serve_p = sub.add_parser(
|
|
34
|
+
"serve",
|
|
35
|
+
help="Start a local HTTP viewer that accepts events on POST /ingest.",
|
|
36
|
+
)
|
|
37
|
+
serve_p.add_argument(
|
|
38
|
+
"--port",
|
|
39
|
+
type=int,
|
|
40
|
+
default=8765,
|
|
41
|
+
metavar="PORT",
|
|
42
|
+
help="Port to listen on (default: 8765).",
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
args = parser.parse_args()
|
|
46
|
+
|
|
47
|
+
if args.command == "tail":
|
|
48
|
+
_cmd_tail(args.file)
|
|
49
|
+
elif args.command == "serve":
|
|
50
|
+
_cmd_serve(args.port)
|
|
51
|
+
else:
|
|
52
|
+
parser.print_help()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# ---------------------------------------------------------------------------
|
|
56
|
+
# tracekit tail
|
|
57
|
+
# ---------------------------------------------------------------------------
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _cmd_tail(path: str) -> None:
|
|
61
|
+
"""Open the JSONL file, seek to end, and print new lines as they appear."""
|
|
62
|
+
try:
|
|
63
|
+
f = open(path, encoding="utf-8") # noqa: SIM115 (kept open intentionally)
|
|
64
|
+
except FileNotFoundError:
|
|
65
|
+
print(f"[tracekit] File not found: {path}", file=sys.stderr)
|
|
66
|
+
sys.exit(1)
|
|
67
|
+
|
|
68
|
+
# Seek to end so we only show events that arrive after `tail` starts.
|
|
69
|
+
f.seek(0, 2)
|
|
70
|
+
print(f"[tracekit tail] Watching {path} … (Ctrl+C to stop)", file=sys.stderr)
|
|
71
|
+
try:
|
|
72
|
+
while True:
|
|
73
|
+
line = f.readline()
|
|
74
|
+
if line:
|
|
75
|
+
_print_event(line.strip())
|
|
76
|
+
else:
|
|
77
|
+
# No new data yet — pause briefly (not sleep-polling: 50 ms is
|
|
78
|
+
# enough for interactive use and costs negligible CPU).
|
|
79
|
+
time.sleep(0.05)
|
|
80
|
+
except KeyboardInterrupt:
|
|
81
|
+
pass
|
|
82
|
+
finally:
|
|
83
|
+
f.close()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _print_event(raw: str) -> None:
|
|
87
|
+
"""
|
|
88
|
+
Format one JSONL line as a human-readable string on stdout.
|
|
89
|
+
|
|
90
|
+
Falls back to printing the raw line if parsing fails.
|
|
91
|
+
"""
|
|
92
|
+
try:
|
|
93
|
+
event = json.loads(raw)
|
|
94
|
+
ts = event.get("timestamp", "")[:19].replace("T", " ")
|
|
95
|
+
etype = event.get("type", "?")
|
|
96
|
+
|
|
97
|
+
if etype == "error":
|
|
98
|
+
exc = event.get("exception", {})
|
|
99
|
+
exc_type = exc.get("type", "Exception")
|
|
100
|
+
exc_msg = exc.get("message", "")
|
|
101
|
+
print(f"[{ts}] ERROR {exc_type}: {exc_msg}")
|
|
102
|
+
|
|
103
|
+
elif etype == "message":
|
|
104
|
+
level = event.get("level", "info").upper().ljust(7)
|
|
105
|
+
print(f"[{ts}] {level} {event.get('message', '')}")
|
|
106
|
+
|
|
107
|
+
elif etype == "span":
|
|
108
|
+
span = event.get("span", {})
|
|
109
|
+
dur = span.get("duration_ms", 0.0)
|
|
110
|
+
status = span.get("status", "ok")
|
|
111
|
+
print(f"[{ts}] SPAN {span.get('name', '?')} ({dur:.2f}ms) {status}")
|
|
112
|
+
|
|
113
|
+
else:
|
|
114
|
+
# Unknown future event types — print compact JSON.
|
|
115
|
+
print(f"[{ts}] {raw}")
|
|
116
|
+
|
|
117
|
+
except Exception:
|
|
118
|
+
# Malformed JSON — always show the raw line so users see something.
|
|
119
|
+
print(raw)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ---------------------------------------------------------------------------
|
|
123
|
+
# tracekit serve
|
|
124
|
+
# ---------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _cmd_serve(port: int) -> None:
|
|
128
|
+
"""Start the local HTTP viewer and block until Ctrl-C."""
|
|
129
|
+
from tracekit.viewer import ViewerServer # noqa: PLC0415
|
|
130
|
+
|
|
131
|
+
server = ViewerServer(port=port)
|
|
132
|
+
server.start()
|
|
133
|
+
url = f"http://127.0.0.1:{port}"
|
|
134
|
+
print(f"[tracekit serve] Listening on {url}", file=sys.stderr)
|
|
135
|
+
ingest = f"{url}/ingest"
|
|
136
|
+
print(f"[tracekit serve] Ingest: {ingest} (POST JSON)", file=sys.stderr)
|
|
137
|
+
print("[tracekit serve] Press Ctrl-C to stop.", file=sys.stderr)
|
|
138
|
+
try:
|
|
139
|
+
while True:
|
|
140
|
+
time.sleep(1)
|
|
141
|
+
except KeyboardInterrupt:
|
|
142
|
+
pass
|
|
143
|
+
finally:
|
|
144
|
+
server.stop()
|
tracekit/client.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""
|
|
2
|
+
client.py — Client: builds events, applies filters, hands to transport.
|
|
3
|
+
|
|
4
|
+
Holds the single module-level _client holder used by the public API.
|
|
5
|
+
No global mutable state other than _client (PRD §1.10).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import sys
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from tracekit.config import Config, parse_output
|
|
14
|
+
from tracekit.event import build_error_event, build_message_event, build_span_event
|
|
15
|
+
from tracekit.filters import apply_filters
|
|
16
|
+
from tracekit.sinks import ConsoleSink, FileSink, HttpSink
|
|
17
|
+
from tracekit.transport import Transport
|
|
18
|
+
|
|
19
|
+
# ---------------------------------------------------------------------------
|
|
20
|
+
# Module-level client holder (the ONE permitted piece of global mutable state).
|
|
21
|
+
# ---------------------------------------------------------------------------
|
|
22
|
+
|
|
23
|
+
_client: Client | None = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _set_client(c: Client | None) -> None:
|
|
27
|
+
"""Replace the active client; called only by tracekit.init()."""
|
|
28
|
+
global _client
|
|
29
|
+
_client = c
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def get_client() -> Client | None:
|
|
33
|
+
"""Return the current client, or None if init() has not been called."""
|
|
34
|
+
return _client
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# ---------------------------------------------------------------------------
|
|
38
|
+
# Client
|
|
39
|
+
# ---------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Client:
|
|
43
|
+
"""
|
|
44
|
+
Co-ordinates event building, (future) filtering, and delivery.
|
|
45
|
+
|
|
46
|
+
One instance exists per init() call; a re-call to init() replaces it.
|
|
47
|
+
Delivery is asynchronous via Transport's daemon worker thread (Phase 5+).
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(self, config: Config) -> None:
|
|
51
|
+
self._config = config
|
|
52
|
+
sink = self._make_sink(config)
|
|
53
|
+
self._transport = Transport(sink)
|
|
54
|
+
|
|
55
|
+
# ------------------------------------------------------------------
|
|
56
|
+
# Public capture methods — both wrapped so SDK errors never escape.
|
|
57
|
+
# ------------------------------------------------------------------
|
|
58
|
+
|
|
59
|
+
def capture_exception(self, exc: BaseException | None = None) -> None:
|
|
60
|
+
"""
|
|
61
|
+
Build and deliver an error event.
|
|
62
|
+
|
|
63
|
+
If exc is None, uses sys.exc_info() so callers inside an except
|
|
64
|
+
block don't need to pass the exception explicitly.
|
|
65
|
+
Never raises.
|
|
66
|
+
"""
|
|
67
|
+
try:
|
|
68
|
+
resolved = exc if exc is not None else sys.exc_info()[1]
|
|
69
|
+
if resolved is None:
|
|
70
|
+
return # no active exception and none supplied — silent no-op
|
|
71
|
+
event = build_error_event(
|
|
72
|
+
resolved,
|
|
73
|
+
environment=self._config.environment,
|
|
74
|
+
release=self._config.release,
|
|
75
|
+
**self._scope_kwargs(),
|
|
76
|
+
)
|
|
77
|
+
self._send(event)
|
|
78
|
+
except Exception as sdk_err:
|
|
79
|
+
self._debug(f"capture_exception internal error: {sdk_err}")
|
|
80
|
+
|
|
81
|
+
def capture_message(self, text: str, level: str = "info") -> None:
|
|
82
|
+
"""Build and deliver a message event. Never raises."""
|
|
83
|
+
try:
|
|
84
|
+
event = build_message_event(
|
|
85
|
+
text,
|
|
86
|
+
level,
|
|
87
|
+
environment=self._config.environment,
|
|
88
|
+
release=self._config.release,
|
|
89
|
+
**self._scope_kwargs(),
|
|
90
|
+
)
|
|
91
|
+
self._send(event)
|
|
92
|
+
except Exception as sdk_err:
|
|
93
|
+
self._debug(f"capture_message internal error: {sdk_err}")
|
|
94
|
+
|
|
95
|
+
def capture_span(
|
|
96
|
+
self, name: str, duration_ms: float, status: str
|
|
97
|
+
) -> None:
|
|
98
|
+
"""Build and deliver a span event. Never raises."""
|
|
99
|
+
try:
|
|
100
|
+
event = build_span_event(
|
|
101
|
+
name,
|
|
102
|
+
duration_ms,
|
|
103
|
+
status,
|
|
104
|
+
environment=self._config.environment,
|
|
105
|
+
release=self._config.release,
|
|
106
|
+
**self._scope_kwargs(),
|
|
107
|
+
)
|
|
108
|
+
self._send(event)
|
|
109
|
+
except Exception as sdk_err:
|
|
110
|
+
self._debug(f"capture_span internal error: {sdk_err}")
|
|
111
|
+
|
|
112
|
+
# ------------------------------------------------------------------
|
|
113
|
+
# flush / shutdown — forwarded to Transport
|
|
114
|
+
# ------------------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
def flush(self, timeout: float = 2.0) -> None:
|
|
117
|
+
"""Block until all queued events are delivered (or timeout expires)."""
|
|
118
|
+
try:
|
|
119
|
+
self._transport.flush(timeout)
|
|
120
|
+
except Exception as sdk_err:
|
|
121
|
+
self._debug(f"flush internal error: {sdk_err}")
|
|
122
|
+
|
|
123
|
+
def shutdown(self) -> None:
|
|
124
|
+
"""Flush and stop the background worker thread. Safe to call multiple times."""
|
|
125
|
+
try:
|
|
126
|
+
self._transport.shutdown()
|
|
127
|
+
except Exception as sdk_err:
|
|
128
|
+
self._debug(f"shutdown internal error: {sdk_err}")
|
|
129
|
+
|
|
130
|
+
# ------------------------------------------------------------------
|
|
131
|
+
# Internal helpers
|
|
132
|
+
# ------------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
def _scope_kwargs(self) -> dict[str, Any]:
|
|
135
|
+
"""
|
|
136
|
+
Read the current context's scope and return only non-empty fields.
|
|
137
|
+
|
|
138
|
+
Imported lazily to keep the import graph acyclic at module load time.
|
|
139
|
+
Never raises — a broken scope must not suppress the event itself.
|
|
140
|
+
"""
|
|
141
|
+
try:
|
|
142
|
+
from tracekit.scope import get_scope_data # noqa: PLC0415
|
|
143
|
+
|
|
144
|
+
data = get_scope_data()
|
|
145
|
+
return {
|
|
146
|
+
k: v
|
|
147
|
+
for k, v in {
|
|
148
|
+
"user": data["user"] or None,
|
|
149
|
+
"tags": data["tags"] or None,
|
|
150
|
+
"breadcrumbs": data["breadcrumbs"] or None,
|
|
151
|
+
}.items()
|
|
152
|
+
if v is not None
|
|
153
|
+
}
|
|
154
|
+
except Exception:
|
|
155
|
+
return {}
|
|
156
|
+
|
|
157
|
+
def _send(self, event: dict[str, Any]) -> None:
|
|
158
|
+
"""Apply filters then enqueue event for background delivery."""
|
|
159
|
+
filtered = apply_filters(
|
|
160
|
+
event,
|
|
161
|
+
sample_rate=self._config.sample_rate,
|
|
162
|
+
ignore_errors=self._config.ignore_errors,
|
|
163
|
+
before_send=self._config.before_send,
|
|
164
|
+
)
|
|
165
|
+
if filtered is not None:
|
|
166
|
+
self._transport.enqueue(filtered)
|
|
167
|
+
|
|
168
|
+
def _debug(self, msg: str) -> None:
|
|
169
|
+
"""Print to stderr only when debug=True, so users never see SDK noise."""
|
|
170
|
+
if self._config.debug:
|
|
171
|
+
print(f"[TraceKit DEBUG] {msg}", file=sys.stderr)
|
|
172
|
+
|
|
173
|
+
@staticmethod
|
|
174
|
+
def _make_sink(config: Config) -> ConsoleSink | FileSink | HttpSink:
|
|
175
|
+
"""
|
|
176
|
+
Construct the appropriate sink from config.output.
|
|
177
|
+
|
|
178
|
+
Supports: console, file:<path>, http://<url>, https://<url>.
|
|
179
|
+
Unknown kinds fall back to ConsoleSink with an optional debug warning.
|
|
180
|
+
"""
|
|
181
|
+
kind, target = parse_output(config.output)
|
|
182
|
+
if kind == "file" and target:
|
|
183
|
+
return FileSink(target)
|
|
184
|
+
if kind in ("http", "https") and target:
|
|
185
|
+
return HttpSink(config.output) # pass the full original URL
|
|
186
|
+
if kind == "console":
|
|
187
|
+
return ConsoleSink()
|
|
188
|
+
# Unknown kind: warn in debug mode and fall back to console.
|
|
189
|
+
if config.debug:
|
|
190
|
+
print(
|
|
191
|
+
f"[TraceKit] Sink '{kind}' not recognised; using ConsoleSink.",
|
|
192
|
+
file=sys.stderr,
|
|
193
|
+
)
|
|
194
|
+
return ConsoleSink()
|
tracekit/config.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""
|
|
2
|
+
config.py — Config dataclass and output-string parsing.
|
|
3
|
+
|
|
4
|
+
Knows nothing about sinks or transport; it only holds settings.
|
|
5
|
+
Parsing lives here so client.py and sinks.py stay decoupled.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Config:
|
|
17
|
+
"""All SDK settings in one immutable-ish place; created once per init() call."""
|
|
18
|
+
|
|
19
|
+
output: str = "console"
|
|
20
|
+
environment: str = "production"
|
|
21
|
+
release: str | None = None
|
|
22
|
+
sample_rate: float = 1.0
|
|
23
|
+
# Exception types or fully-qualified names (e.g. "ValueError") to skip.
|
|
24
|
+
ignore_errors: list[type[BaseException] | str] = field(default_factory=list)
|
|
25
|
+
# Return None from before_send to drop an event entirely.
|
|
26
|
+
before_send: Callable[[dict[str, Any]], dict[str, Any] | None] | None = None
|
|
27
|
+
debug: bool = False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_output(output: str) -> tuple[str, str]:
|
|
31
|
+
"""
|
|
32
|
+
Split an output string into (kind, target).
|
|
33
|
+
|
|
34
|
+
"console" → ("console", "")
|
|
35
|
+
"file:events.jsonl" → ("file", "events.jsonl")
|
|
36
|
+
"http://host/ingest" → ("http", "http://host/ingest")
|
|
37
|
+
"https://…" → ("http", "https://…")
|
|
38
|
+
|
|
39
|
+
Unknown strings fall back to ("console", "") so the app never crashes.
|
|
40
|
+
"""
|
|
41
|
+
if output == "console":
|
|
42
|
+
return ("console", "")
|
|
43
|
+
if output.startswith("file:"):
|
|
44
|
+
return ("file", output[len("file:") :])
|
|
45
|
+
if output.startswith("http://") or output.startswith("https://"):
|
|
46
|
+
return ("http", output)
|
|
47
|
+
return ("console", "")
|