teploy-observe 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.
@@ -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