teploy-observe 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Observe project
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.2
2
+ Name: teploy-observe
3
+ Version: 0.1.0
4
+ Summary: Python SDK for Observe — self-hosted analytics, errors, logs, traces.
5
+ Author: Observe
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/useteploy/teploy-observe
8
+ Project-URL: Repository, https://github.com/useteploy/teploy-observe
9
+ Keywords: analytics,observability,errors,logs,self-hosted
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Topic :: System :: Monitoring
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+
20
+ # teploy-observe (Python)
21
+
22
+ Python SDK for [Observe](https://github.com/useteploy/teploy-observe) — self-hosted analytics, errors, logs, traces.
23
+
24
+ ## Install
25
+
26
+ ```
27
+ pip install teploy-observe
28
+ ```
29
+
30
+ <!-- not-yet-published: delete this block once teploy-observe is on PyPI -->
31
+ > **Not yet published to PyPI.** Until it is, `pip install teploy-observe`
32
+ > fails, and a package of that name that appears on PyPI before this note is
33
+ > removed is not from this project. Install from this repository instead:
34
+ >
35
+ > ```sh
36
+ > pip install "git+https://github.com/useteploy/teploy-observe#subdirectory=sdk/python"
37
+ > # or, from a clone of this repository:
38
+ > pip install ./sdk/python
39
+ > ```
40
+ <!-- /not-yet-published -->
41
+
42
+ Zero dependencies; stdlib only.
43
+
44
+ ## Usage
45
+
46
+ ```python
47
+ import os
48
+ import observe_sdk as observe
49
+
50
+ observe.init(
51
+ endpoint="https://observe.example.com",
52
+ api_key=os.environ["OBSERVE_API_KEY"],
53
+ site_id="default",
54
+ release="v1.4.2",
55
+ service_name="api",
56
+ )
57
+
58
+ try:
59
+ do_work()
60
+ except Exception as exc:
61
+ observe.capture_exception(exc)
62
+
63
+ observe.info("request served", user_id=user_id, duration_ms=elapsed)
64
+
65
+ # Call on shutdown — also registered via atexit so this is optional.
66
+ observe.close()
67
+ ```
68
+
69
+ ## API
70
+
71
+ | function | purpose |
72
+ |----------|---------|
73
+ | `init(...)` | Create and register the module-level client. |
74
+ | `capture_exception(exc)` | Submit an error with stack trace. |
75
+ | `log(level, msg, **fields)` | Emit a log. |
76
+ | `debug / info / warn / error / fatal` | Level helpers. |
77
+ | `flush(timeout=None)` | Drain buffered logs synchronously under an optional whole-drain deadline. |
78
+ | `close(timeout=None)` | Stop the flush thread and drain; incomplete close raises and leaves records queued for a later close. |
79
+ | `stats()` | O11 diagnostics: delivered / retries / dropped-by-reason counters + live queue depth. |
80
+
81
+ ## Guarantees
82
+
83
+ - **Non-blocking logs.** Entries buffer in memory and flush on a timer or when the batch fills.
84
+ - **Immediate errors.** Exceptions ship before a crash can lose them.
85
+ - **Stack traces.** Frames under `site-packages` / stdlib are marked `in_app: false`.
86
+ - **No external deps.** Uses `urllib` + `threading` — fine in Lambda, Docker slim, etc.
87
+
88
+ ## Delivery, loss, and shutdown semantics (O11)
89
+
90
+ - **Bounded queue** (8 MiB queued bytes; per-entry 64 KiB at admission).
91
+ Overflow raises `BufferError` (drop-newest policy) AND counts a visible
92
+ `queue_full` loss in `stats()`.
93
+ - **Bounded retry with backoff**: retryable failures (429/5xx/network) get
94
+ an immediate first retry, then exponential backoff
95
+ (`retry_backoff`, default 1 s, 30 s cap) up to `max_send_attempts`
96
+ (default 6) before the chunk is dropped and counted
97
+ (`retry_exhausted`). A non-retryable 4xx drops its chunk immediately
98
+ (`non_retryable`) — it can never succeed as-shaped.
99
+ - **Partial errors**: the batch ack's per-entry `rejected` count becomes a
100
+ `server_rejected` loss; the accepted neighbors are never resent.
101
+ - **Shutdown**: `close(timeout=...)` bounds worker join and drain;
102
+ one deadline covers ownership waits, worker join, and drain. An incomplete
103
+ close raises `TimeoutError`; retained records stay in `stats()["queued"]`
104
+ and a later close can deliver them. Signal recipe:
105
+
106
+ ```python
107
+ import signal, observe_sdk
108
+
109
+ def _shutdown(signum, frame):
110
+ try:
111
+ observe_sdk.close(timeout=5.0)
112
+ except TimeoutError as exc:
113
+ print(f"observe losses: {observe_sdk.stats()}", file=sys.stderr)
114
+ raise SystemExit(0)
115
+
116
+ signal.signal(signal.SIGTERM, _shutdown)
117
+ signal.signal(signal.SIGINT, _shutdown)
118
+ ```
119
+
120
+ - Queues are in-memory; `kill -9` loses the queue and its counters with
121
+ the process. No durable local spool is claimed.
122
+
123
+ ## Configuration from the environment
124
+
125
+ Options left unset fall back to the environment, so a platform can configure an
126
+ app without code changes. An explicit keyword wins, then `OBSERVE_*`, then the
127
+ OpenTelemetry names:
128
+
129
+ | Option | Environment |
130
+ |---|---|
131
+ | `endpoint` | `OBSERVE_ENDPOINT`, then `OTEL_EXPORTER_OTLP_ENDPOINT` |
132
+ | `api_key` | `OBSERVE_API_KEY`, or `x-api-key` in `OTEL_EXPORTER_OTLP_HEADERS` |
133
+ | `service_name` | `OTEL_SERVICE_NAME`, then `service.name` in `OTEL_RESOURCE_ATTRIBUTES` |
134
+ | `release` | `service.version` in `OTEL_RESOURCE_ATTRIBUTES` |
135
+ | `environment` | `deployment.environment.name` or `deployment.environment` in `OTEL_RESOURCE_ATTRIBUTES` |
136
+
137
+ A credential only goes where it was issued for. An explicit endpoint takes
138
+ `OBSERVE_API_KEY` only if `OBSERVE_ENDPOINT` is unset or names the same place.
139
+ `OTEL_EXPORTER_OTLP_ENDPOINT` is used only when `OTEL_EXPORTER_OTLP_HEADERS` carries
140
+ `x-api-key` and no key was passed in code; otherwise it is treated as another vendor's
141
+ collector, and with nothing else set the client refuses to start.
142
+ `OTEL_EXPORTER_OTLP_PROTOCOL=grpc` disables the OTLP endpoint, since this client speaks
143
+ HTTP.
144
+
145
+ With a key, leave the site unset: the key is bound to one site on the server and a
146
+ different site is refused with a 403. The site defaults to `default` only with no key.
147
+
148
+ ## Breadcrumbs
149
+
150
+ ```python
151
+ observe.init(endpoint=..., api_key=..., max_breadcrumbs=100,
152
+ logging_breadcrumbs=True, # opt-in: logging >= WARNING
153
+ logging_breadcrumb_level=logging.WARNING,
154
+ before_breadcrumb=lambda c: None if c["category"] == "noisy" else c)
155
+ observe.add_breadcrumb("cache miss", category="db", level="warning", data={"key": "u:1"})
156
+ observe.capture_message("slow job", level="warning")
157
+ ```
158
+
159
+ The buffer is a thread-safe, process-wide ring (not request-scoped) attached
160
+ to `capture_exception` / `capture_message`. `logging_breadcrumbs` installs one
161
+ handler on the root logger (removed by `close()`); `client.install_logging_breadcrumbs(level, logger)`
162
+ targets another logger. Records from `observe_sdk` itself are skipped. A
163
+ `before_breadcrumb` that raises drops the breadcrumb.
164
+
165
+ ## Feature flags
166
+
167
+ ```python
168
+ r = observe.evaluate_flag("new-checkout", user_id="u1",
169
+ attributes={"plan": "pro"}, default={"enabled": False})
170
+ # {"key", "enabled", "variant"?, "reason", "source": "server" | "default", "error"?}
171
+ ```
172
+
173
+ `POST /api/v1/flags/evaluate` over the client's transport (no redirects, API
174
+ key header). Default timeout is min(client timeout, 3 s). Never raises:
175
+ failures, timeouts and server fail-safe answers return `default` with
176
+ `source == "default"`. No cache, no exposure event. See
177
+ `docs/sdk/BREADCRUMBS_FLAGS.md`.
178
+
179
+ ## License
180
+
181
+ MIT
@@ -0,0 +1,162 @@
1
+ # teploy-observe (Python)
2
+
3
+ Python SDK for [Observe](https://github.com/useteploy/teploy-observe) — self-hosted analytics, errors, logs, traces.
4
+
5
+ ## Install
6
+
7
+ ```
8
+ pip install teploy-observe
9
+ ```
10
+
11
+ <!-- not-yet-published: delete this block once teploy-observe is on PyPI -->
12
+ > **Not yet published to PyPI.** Until it is, `pip install teploy-observe`
13
+ > fails, and a package of that name that appears on PyPI before this note is
14
+ > removed is not from this project. Install from this repository instead:
15
+ >
16
+ > ```sh
17
+ > pip install "git+https://github.com/useteploy/teploy-observe#subdirectory=sdk/python"
18
+ > # or, from a clone of this repository:
19
+ > pip install ./sdk/python
20
+ > ```
21
+ <!-- /not-yet-published -->
22
+
23
+ Zero dependencies; stdlib only.
24
+
25
+ ## Usage
26
+
27
+ ```python
28
+ import os
29
+ import observe_sdk as observe
30
+
31
+ observe.init(
32
+ endpoint="https://observe.example.com",
33
+ api_key=os.environ["OBSERVE_API_KEY"],
34
+ site_id="default",
35
+ release="v1.4.2",
36
+ service_name="api",
37
+ )
38
+
39
+ try:
40
+ do_work()
41
+ except Exception as exc:
42
+ observe.capture_exception(exc)
43
+
44
+ observe.info("request served", user_id=user_id, duration_ms=elapsed)
45
+
46
+ # Call on shutdown — also registered via atexit so this is optional.
47
+ observe.close()
48
+ ```
49
+
50
+ ## API
51
+
52
+ | function | purpose |
53
+ |----------|---------|
54
+ | `init(...)` | Create and register the module-level client. |
55
+ | `capture_exception(exc)` | Submit an error with stack trace. |
56
+ | `log(level, msg, **fields)` | Emit a log. |
57
+ | `debug / info / warn / error / fatal` | Level helpers. |
58
+ | `flush(timeout=None)` | Drain buffered logs synchronously under an optional whole-drain deadline. |
59
+ | `close(timeout=None)` | Stop the flush thread and drain; incomplete close raises and leaves records queued for a later close. |
60
+ | `stats()` | O11 diagnostics: delivered / retries / dropped-by-reason counters + live queue depth. |
61
+
62
+ ## Guarantees
63
+
64
+ - **Non-blocking logs.** Entries buffer in memory and flush on a timer or when the batch fills.
65
+ - **Immediate errors.** Exceptions ship before a crash can lose them.
66
+ - **Stack traces.** Frames under `site-packages` / stdlib are marked `in_app: false`.
67
+ - **No external deps.** Uses `urllib` + `threading` — fine in Lambda, Docker slim, etc.
68
+
69
+ ## Delivery, loss, and shutdown semantics (O11)
70
+
71
+ - **Bounded queue** (8 MiB queued bytes; per-entry 64 KiB at admission).
72
+ Overflow raises `BufferError` (drop-newest policy) AND counts a visible
73
+ `queue_full` loss in `stats()`.
74
+ - **Bounded retry with backoff**: retryable failures (429/5xx/network) get
75
+ an immediate first retry, then exponential backoff
76
+ (`retry_backoff`, default 1 s, 30 s cap) up to `max_send_attempts`
77
+ (default 6) before the chunk is dropped and counted
78
+ (`retry_exhausted`). A non-retryable 4xx drops its chunk immediately
79
+ (`non_retryable`) — it can never succeed as-shaped.
80
+ - **Partial errors**: the batch ack's per-entry `rejected` count becomes a
81
+ `server_rejected` loss; the accepted neighbors are never resent.
82
+ - **Shutdown**: `close(timeout=...)` bounds worker join and drain;
83
+ one deadline covers ownership waits, worker join, and drain. An incomplete
84
+ close raises `TimeoutError`; retained records stay in `stats()["queued"]`
85
+ and a later close can deliver them. Signal recipe:
86
+
87
+ ```python
88
+ import signal, observe_sdk
89
+
90
+ def _shutdown(signum, frame):
91
+ try:
92
+ observe_sdk.close(timeout=5.0)
93
+ except TimeoutError as exc:
94
+ print(f"observe losses: {observe_sdk.stats()}", file=sys.stderr)
95
+ raise SystemExit(0)
96
+
97
+ signal.signal(signal.SIGTERM, _shutdown)
98
+ signal.signal(signal.SIGINT, _shutdown)
99
+ ```
100
+
101
+ - Queues are in-memory; `kill -9` loses the queue and its counters with
102
+ the process. No durable local spool is claimed.
103
+
104
+ ## Configuration from the environment
105
+
106
+ Options left unset fall back to the environment, so a platform can configure an
107
+ app without code changes. An explicit keyword wins, then `OBSERVE_*`, then the
108
+ OpenTelemetry names:
109
+
110
+ | Option | Environment |
111
+ |---|---|
112
+ | `endpoint` | `OBSERVE_ENDPOINT`, then `OTEL_EXPORTER_OTLP_ENDPOINT` |
113
+ | `api_key` | `OBSERVE_API_KEY`, or `x-api-key` in `OTEL_EXPORTER_OTLP_HEADERS` |
114
+ | `service_name` | `OTEL_SERVICE_NAME`, then `service.name` in `OTEL_RESOURCE_ATTRIBUTES` |
115
+ | `release` | `service.version` in `OTEL_RESOURCE_ATTRIBUTES` |
116
+ | `environment` | `deployment.environment.name` or `deployment.environment` in `OTEL_RESOURCE_ATTRIBUTES` |
117
+
118
+ A credential only goes where it was issued for. An explicit endpoint takes
119
+ `OBSERVE_API_KEY` only if `OBSERVE_ENDPOINT` is unset or names the same place.
120
+ `OTEL_EXPORTER_OTLP_ENDPOINT` is used only when `OTEL_EXPORTER_OTLP_HEADERS` carries
121
+ `x-api-key` and no key was passed in code; otherwise it is treated as another vendor's
122
+ collector, and with nothing else set the client refuses to start.
123
+ `OTEL_EXPORTER_OTLP_PROTOCOL=grpc` disables the OTLP endpoint, since this client speaks
124
+ HTTP.
125
+
126
+ With a key, leave the site unset: the key is bound to one site on the server and a
127
+ different site is refused with a 403. The site defaults to `default` only with no key.
128
+
129
+ ## Breadcrumbs
130
+
131
+ ```python
132
+ observe.init(endpoint=..., api_key=..., max_breadcrumbs=100,
133
+ logging_breadcrumbs=True, # opt-in: logging >= WARNING
134
+ logging_breadcrumb_level=logging.WARNING,
135
+ before_breadcrumb=lambda c: None if c["category"] == "noisy" else c)
136
+ observe.add_breadcrumb("cache miss", category="db", level="warning", data={"key": "u:1"})
137
+ observe.capture_message("slow job", level="warning")
138
+ ```
139
+
140
+ The buffer is a thread-safe, process-wide ring (not request-scoped) attached
141
+ to `capture_exception` / `capture_message`. `logging_breadcrumbs` installs one
142
+ handler on the root logger (removed by `close()`); `client.install_logging_breadcrumbs(level, logger)`
143
+ targets another logger. Records from `observe_sdk` itself are skipped. A
144
+ `before_breadcrumb` that raises drops the breadcrumb.
145
+
146
+ ## Feature flags
147
+
148
+ ```python
149
+ r = observe.evaluate_flag("new-checkout", user_id="u1",
150
+ attributes={"plan": "pro"}, default={"enabled": False})
151
+ # {"key", "enabled", "variant"?, "reason", "source": "server" | "default", "error"?}
152
+ ```
153
+
154
+ `POST /api/v1/flags/evaluate` over the client's transport (no redirects, API
155
+ key header). Default timeout is min(client timeout, 3 s). Never raises:
156
+ failures, timeouts and server fail-safe answers return `default` with
157
+ `source == "default"`. No cache, no exposure event. See
158
+ `docs/sdk/BREADCRUMBS_FLAGS.md`.
159
+
160
+ ## License
161
+
162
+ MIT
@@ -0,0 +1,62 @@
1
+ """Observe Python SDK — self-hosted analytics, errors, logs, traces.
2
+
3
+ Quick start:
4
+
5
+ import observe_sdk as observe
6
+
7
+ observe.init(
8
+ endpoint="https://observe.example.com",
9
+ api_key=os.environ["OBSERVE_API_KEY"],
10
+ site_id="default",
11
+ release="v1.4.2",
12
+ )
13
+
14
+ try:
15
+ do_work()
16
+ except Exception as exc:
17
+ observe.capture_exception(exc)
18
+
19
+ observe.info("request served", user_id=user_id, duration_ms=elapsed)
20
+
21
+ observe.close() # flushes buffered logs
22
+ """
23
+
24
+ from .client import (
25
+ Client,
26
+ init,
27
+ close,
28
+ flush,
29
+ stats,
30
+ capture_exception,
31
+ capture_message,
32
+ add_breadcrumb,
33
+ clear_breadcrumbs,
34
+ evaluate_flag,
35
+ log,
36
+ debug,
37
+ info,
38
+ warn,
39
+ error,
40
+ fatal,
41
+ )
42
+
43
+ __all__ = [
44
+ "Client",
45
+ "init",
46
+ "close",
47
+ "flush",
48
+ "stats",
49
+ "capture_exception",
50
+ "capture_message",
51
+ "add_breadcrumb",
52
+ "clear_breadcrumbs",
53
+ "evaluate_flag",
54
+ "log",
55
+ "debug",
56
+ "info",
57
+ "warn",
58
+ "error",
59
+ "fatal",
60
+ ]
61
+
62
+ __version__ = "0.1.0"
@@ -0,0 +1,191 @@
1
+ """Breadcrumbs: a bounded record of what happened before an error.
2
+
3
+ The wire shape matches the server's error ingest (internal/errors
4
+ Breadcrumb): ``type``, ``category``, ``message``, ``data``, ``timestamp``
5
+ (Unix epoch milliseconds) and ``level``.
6
+
7
+ The buffer is process-wide and thread-safe. It is a ring: once full, the
8
+ oldest entry is dropped. It is not request-scoped, so on a server handling
9
+ concurrent requests the breadcrumbs attached to an error are the most
10
+ recent activity of the whole process, not of one request.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import collections
16
+ import json
17
+ import logging
18
+ import threading
19
+ import time
20
+ from typing import Any, Callable, Deque, Dict, List, Optional
21
+
22
+ DEFAULT_MAX_BREADCRUMBS = 100
23
+ MAX_MESSAGE = 256
24
+ MAX_DATA_BYTES = 1024
25
+ # Budget for the breadcrumbs attached to one payload; oldest are dropped first.
26
+ MAX_ATTACH_BYTES = 32 * 1024
27
+
28
+ _LEVELS = ("debug", "info", "warning", "error")
29
+
30
+ BeforeBreadcrumb = Callable[[Dict[str, Any]], Optional[Dict[str, Any]]]
31
+
32
+
33
+ def _clone_data(data: Any) -> Optional[Dict[str, Any]]:
34
+ """Own-data snapshot via a JSON round trip, size-capped."""
35
+ if data is None:
36
+ return None
37
+ try:
38
+ raw = json.dumps(data, default=str, allow_nan=False)
39
+ except (TypeError, ValueError):
40
+ return {"_unserializable": True}
41
+ if len(raw) > MAX_DATA_BYTES:
42
+ return {"_truncated": True, "_bytes": len(raw)}
43
+ out = json.loads(raw)
44
+ return out if isinstance(out, dict) else {"value": out}
45
+
46
+
47
+ def _level(value: Any, default: str = "info") -> str:
48
+ return value if isinstance(value, str) and value in _LEVELS else default
49
+
50
+
51
+ class BreadcrumbBuffer:
52
+ """Thread-safe bounded ring of breadcrumbs."""
53
+
54
+ def __init__(
55
+ self,
56
+ max_size: int = DEFAULT_MAX_BREADCRUMBS,
57
+ before_breadcrumb: Optional[BeforeBreadcrumb] = None,
58
+ on_error: Optional[Callable[[BaseException], None]] = None,
59
+ ) -> None:
60
+ self._lock = threading.Lock()
61
+ self._items: Deque[Dict[str, Any]] = collections.deque(maxlen=max_size)
62
+ self._before = before_breadcrumb
63
+ self._on_error = on_error
64
+
65
+ def add(
66
+ self,
67
+ message: str,
68
+ *,
69
+ category: str = "default",
70
+ type: str = "default", # noqa: A002 - wire field name
71
+ level: str = "info",
72
+ data: Optional[Dict[str, Any]] = None,
73
+ timestamp: Optional[int] = None,
74
+ ) -> None:
75
+ """Record a breadcrumb. Never raises."""
76
+ try:
77
+ crumb: Dict[str, Any] = {
78
+ "type": str(type)[:64],
79
+ "category": str(category)[:64],
80
+ "message": str(message)[:MAX_MESSAGE],
81
+ "timestamp": int(timestamp) if isinstance(timestamp, (int, float)) and not isinstance(timestamp, bool)
82
+ else int(time.time() * 1000),
83
+ "level": _level(level),
84
+ }
85
+ cloned = _clone_data(data)
86
+ if cloned is not None:
87
+ crumb["data"] = cloned
88
+ if self._before is not None:
89
+ try:
90
+ edited = self._before(crumb)
91
+ except Exception as exc: # noqa: BLE001
92
+ # Fail closed: the hook is usually a scrubber.
93
+ self._report(exc)
94
+ return
95
+ if not edited:
96
+ return
97
+ crumb = {
98
+ "type": str(edited.get("type", crumb["type"]))[:64],
99
+ "category": str(edited.get("category", crumb["category"]))[:64],
100
+ "message": str(edited.get("message", ""))[:MAX_MESSAGE],
101
+ "timestamp": edited.get("timestamp", crumb["timestamp"])
102
+ if isinstance(edited.get("timestamp"), int) else crumb["timestamp"],
103
+ "level": _level(edited.get("level"), crumb["level"]),
104
+ }
105
+ cloned = _clone_data(edited.get("data"))
106
+ if cloned is not None:
107
+ crumb["data"] = cloned
108
+ with self._lock:
109
+ self._items.append(crumb)
110
+ except Exception: # noqa: BLE001 - recording must never break the caller
111
+ pass
112
+
113
+ def _report(self, exc: BaseException) -> None:
114
+ if self._on_error is not None:
115
+ try:
116
+ self._on_error(exc)
117
+ except Exception: # noqa: BLE001
118
+ pass
119
+
120
+ def snapshot(self) -> List[Dict[str, Any]]:
121
+ """Oldest-first copy, bounded to the attach byte budget."""
122
+ with self._lock:
123
+ items = list(self._items)
124
+ out: List[Dict[str, Any]] = []
125
+ used = 2
126
+ for crumb in reversed(items):
127
+ size = len(json.dumps(crumb)) + 1
128
+ if used + size > MAX_ATTACH_BYTES:
129
+ break
130
+ used += size
131
+ copy = dict(crumb)
132
+ if "data" in copy:
133
+ copy["data"] = json.loads(json.dumps(copy["data"], allow_nan=False))
134
+ out.append(copy)
135
+ out.reverse()
136
+ return out
137
+
138
+ def clear(self) -> None:
139
+ with self._lock:
140
+ self._items.clear()
141
+
142
+ def __len__(self) -> int:
143
+ with self._lock:
144
+ return len(self._items)
145
+
146
+
147
+ _PY_LEVELS = (
148
+ (logging.ERROR, "error"),
149
+ (logging.WARNING, "warning"),
150
+ (logging.INFO, "info"),
151
+ )
152
+
153
+
154
+ class BreadcrumbHandler(logging.Handler):
155
+ """``logging`` handler that records records as breadcrumbs.
156
+
157
+ Records from the SDK's own logger (``observe_sdk``) are skipped so the
158
+ SDK cannot record its own diagnostics, and a thread-local guard stops
159
+ recursion if a ``before_breadcrumb`` hook logs.
160
+ """
161
+
162
+ def __init__(self, buffer: BreadcrumbBuffer, level: int = logging.WARNING) -> None:
163
+ super().__init__(level=level)
164
+ self._buffer = buffer
165
+ self._guard = threading.local()
166
+
167
+ def emit(self, record: logging.LogRecord) -> None:
168
+ try:
169
+ if record.name == "observe_sdk" or record.name.startswith("observe_sdk."):
170
+ return
171
+ if getattr(self._guard, "active", False):
172
+ return
173
+ self._guard.active = True
174
+ try:
175
+ level = "debug"
176
+ for threshold, name in _PY_LEVELS:
177
+ if record.levelno >= threshold:
178
+ level = name
179
+ break
180
+ self._buffer.add(
181
+ record.getMessage(),
182
+ type="log",
183
+ category=record.name,
184
+ level=level,
185
+ data={"logger": record.name, "level_name": record.levelname},
186
+ timestamp=int(record.created * 1000),
187
+ )
188
+ finally:
189
+ self._guard.active = False
190
+ except Exception: # noqa: BLE001 - logging handlers must not raise
191
+ pass