loggerai-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.
loggerai/__init__.py ADDED
@@ -0,0 +1,122 @@
1
+ """
2
+ LoggerAI for Python: performance monitoring, errors, logs and health checks
3
+ for FastAPI, Starlette, Django, Flask and Celery.
4
+
5
+ import loggerai
6
+ loggerai.init() # reads LOGGERAI_KEY (sk_live_...)
7
+
8
+ # FastAPI / Starlette
9
+ from loggerai.asgi import LoggerAIMiddleware
10
+ app.add_middleware(LoggerAIMiddleware)
11
+
12
+ Nothing is sent without a key, nothing ever raises into your app, and
13
+ secrets are masked before anything leaves it.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import contextlib
18
+ import time
19
+ from typing import Any, Callable, Dict, Iterator, Optional
20
+
21
+ from . import context
22
+ from ._version import __version__
23
+ from .client import Client, get_client, set_client
24
+
25
+ __all__ = ["init", "capture_exception", "set_user", "set_route", "measure", "track", "flush", "health_checks", "Client", "__version__"]
26
+
27
+
28
+ def init(key: Optional[str] = None, **options: Any) -> Client:
29
+ """Start LoggerAI. Every option also has an environment variable:
30
+ key (LOGGERAI_KEY), endpoint, service, environment, release, enabled.
31
+ Others: logs_level ("WARNING", or None for no logs), capture_queries,
32
+ capture_http, capture_redis, ignore_paths, health_checks={"database": fn},
33
+ flush_interval (seconds), timeout, root (the app's folder, for stack traces)."""
34
+ old = get_client()
35
+ if old is not None:
36
+ old.close(timeout=1.0)
37
+ client = Client(key, **options)
38
+ set_client(client)
39
+ if client.enabled:
40
+ from . import instrument
41
+ instrument.all_from(client)
42
+ if client.health_checks:
43
+ client.start()
44
+ return client
45
+
46
+
47
+ def capture_exception(exc: Optional[BaseException] = None, **extra: Any) -> None:
48
+ """Report an exception you handled but still want to see."""
49
+ import sys
50
+ exc = exc or sys.exc_info()[1]
51
+ client = get_client()
52
+ if exc is not None and client is not None:
53
+ client.exception(exc, handled=True, extra=extra or None)
54
+
55
+
56
+ def set_user(user_id: Any) -> None:
57
+ """Count the current request against a user. Only a one-way hash of the id is sent."""
58
+ unit, client = context.current.get(), get_client()
59
+ if unit is not None and client is not None:
60
+ unit.user = client.user_ref(user_id)
61
+
62
+
63
+ def set_route(template: str) -> None:
64
+ """Name the current request yourself (a template like /orders/{id}, never a raw path)."""
65
+ unit = context.current.get()
66
+ if unit is not None:
67
+ unit.route = template
68
+
69
+
70
+ @contextlib.contextmanager
71
+ def measure(target: str, operation: str = "CALL") -> Iterator[None]:
72
+ """Time a call LoggerAI can't see on its own, e.g. an SDK with its own HTTP client:
73
+
74
+ with loggerai.measure("api.stripe.com", "POST"):
75
+ stripe.PaymentIntent.confirm(...)
76
+ """
77
+ t = time.perf_counter()
78
+ ok = False
79
+ try:
80
+ yield
81
+ ok = True
82
+ finally:
83
+ context.dependency(target, operation, (time.perf_counter() - t) * 1000, ok)
84
+
85
+
86
+ @contextlib.contextmanager
87
+ def track(kind: str, name: str) -> Iterator[context.Unit]:
88
+ """Time a unit of work outside a web request: a job, a scheduled task, a script.
89
+
90
+ with loggerai.track("job", "send_invoices"):
91
+ ...
92
+ """
93
+ client = get_client()
94
+ unit = context.Unit(kind if kind in ("job", "command", "http") else "job", "JOB" if kind != "command" else "CLI")
95
+ unit.route = name
96
+ token = context.current.set(unit)
97
+ status = 200
98
+ try:
99
+ yield unit
100
+ except Exception as e:
101
+ status = 500
102
+ if client is not None:
103
+ client.exception(e, status=500)
104
+ raise
105
+ finally:
106
+ context.current.reset(token)
107
+ if client is not None:
108
+ client.finish(unit, status)
109
+
110
+
111
+ def flush(timeout: float = 5.0) -> bool:
112
+ """Send everything now (e.g. at the end of a script or a serverless call)."""
113
+ client = get_client()
114
+ return client.flush(timeout) if client is not None else True
115
+
116
+
117
+ def health_checks(checks: Dict[str, Callable[[], Any]]) -> None:
118
+ """Add health checks after init: each returns True/False, or (ok, detail)."""
119
+ client = get_client()
120
+ if client is not None:
121
+ client.health_checks.update(checks)
122
+ client.start()
loggerai/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
loggerai/asgi.py ADDED
@@ -0,0 +1,60 @@
1
+ """ASGI middleware: FastAPI, Starlette, and any ASGI app.
2
+
3
+ from loggerai.asgi import LoggerAIMiddleware
4
+ app.add_middleware(LoggerAIMiddleware)
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from . import context
9
+ from .client import get_client
10
+
11
+
12
+ def _route(scope) -> str | None:
13
+ route = scope.get("route")
14
+ if route is not None:
15
+ path = getattr(route, "path_format", None) or getattr(route, "path", None)
16
+ if path:
17
+ # Routes inside a mounted sub-app are relative to the mount.
18
+ mount = scope.get("app_root_path") or ""
19
+ return (mount.rstrip("/") + path) if mount and not path.startswith(mount) else path
20
+ endpoint = scope.get("endpoint")
21
+ app = scope.get("app")
22
+ if endpoint is not None and app is not None: # older Starlette: find the route by its endpoint
23
+ for r in getattr(app, "routes", []) or []:
24
+ if getattr(r, "endpoint", None) is endpoint:
25
+ return getattr(r, "path_format", None) or getattr(r, "path", None)
26
+ return None
27
+
28
+
29
+ class LoggerAIMiddleware:
30
+ def __init__(self, app):
31
+ self.app = app
32
+
33
+ async def __call__(self, scope, receive, send):
34
+ client = get_client()
35
+ if scope["type"] != "http" or client is None or not client.enabled or client.ignored(scope.get("path", "")):
36
+ return await self.app(scope, receive, send)
37
+ headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers") or []}
38
+ unit = context.Unit("http", scope.get("method", "GET"), context.trace_from(headers.get("traceparent")),
39
+ context.session_from(headers.get("x-loggerai-session")))
40
+ token = context.current.set(unit)
41
+ status = 500
42
+
43
+ async def _send(message):
44
+ nonlocal status
45
+ if message["type"] == "http.response.start":
46
+ status = message["status"]
47
+ await send(message)
48
+
49
+ try:
50
+ await self.app(scope, receive, _send)
51
+ except BaseException as e:
52
+ unit.route = unit.route or _route(scope)
53
+ if isinstance(e, Exception):
54
+ client.exception(e, status=500)
55
+ status = 500
56
+ raise
57
+ finally:
58
+ unit.route = unit.route or _route(scope)
59
+ context.current.reset(token)
60
+ client.finish(unit, status)
loggerai/celery.py ADDED
@@ -0,0 +1,44 @@
1
+ """Celery: every task timed like a request (kind "job"), failures reported.
2
+
3
+ import loggerai, loggerai.celery
4
+ loggerai.init()
5
+ loggerai.celery.instrument()
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from . import context
10
+ from .client import get_client
11
+
12
+ _tokens = {}
13
+
14
+
15
+ def instrument() -> None:
16
+ from celery import signals
17
+
18
+ @signals.task_prerun.connect(weak=False)
19
+ def _start(task_id=None, task=None, **kw):
20
+ client = get_client()
21
+ if client is None or not client.enabled:
22
+ return
23
+ unit = context.Unit("job", "JOB")
24
+ unit.route = getattr(task, "name", None) or "task"
25
+ _tokens[task_id] = (unit, context.current.set(unit))
26
+
27
+ @signals.task_failure.connect(weak=False)
28
+ def _failed(task_id=None, exception=None, **kw):
29
+ client = get_client()
30
+ if client is not None and exception is not None:
31
+ client.exception(exception, status=500)
32
+
33
+ @signals.task_postrun.connect(weak=False)
34
+ def _end(task_id=None, state=None, **kw):
35
+ got = _tokens.pop(task_id, None)
36
+ client = get_client()
37
+ if got is None or client is None:
38
+ return
39
+ unit, token = got
40
+ try:
41
+ context.current.reset(token)
42
+ except ValueError:
43
+ context.current.set(None)
44
+ client.finish(unit, 200 if state == "SUCCESS" else 500)
loggerai/client.py ADDED
@@ -0,0 +1,284 @@
1
+ """
2
+ The client: settings, the buffer, and a background thread that sends batches
3
+ to LoggerAI every few seconds. Nothing here ever raises into the app or makes
4
+ a request wait; when LoggerAI can't be reached, records are dropped rather
5
+ than piling up.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import atexit
10
+ import gzip
11
+ import hashlib
12
+ import hmac
13
+ import json
14
+ import logging
15
+ import os
16
+ import socket
17
+ import threading
18
+ import time
19
+ import urllib.error
20
+ import urllib.request
21
+ from typing import Callable, Dict, List, Optional
22
+
23
+ from . import context
24
+ from ._version import __version__
25
+ from .frames import frames, type_name
26
+ from .redact import redact, redact_string
27
+
28
+ log = logging.getLogger("loggerai")
29
+
30
+ DEFAULT_ENDPOINT = "https://loggerapp.ehigiator.com/api/v1/ingest/batch"
31
+ KINDS = ("requests", "errors", "logs", "checks")
32
+ MAX_BUFFER = 10_000 # per kind; beyond this the oldest go
33
+ MAX_PER_BATCH = 1_000 # the server's limit per kind
34
+ MAX_BATCH_BYTES = 900_000 # under the server's 1 MB
35
+
36
+
37
+ def _env(name: str, default: Optional[str] = None) -> Optional[str]:
38
+ v = os.environ.get(name)
39
+ return v if v not in (None, "") else default
40
+
41
+
42
+ def _truthy(v) -> bool:
43
+ return str(v).strip().lower() not in ("0", "false", "no", "off", "")
44
+
45
+
46
+ class Client:
47
+ def __init__(
48
+ self,
49
+ key: Optional[str] = None,
50
+ *,
51
+ endpoint: Optional[str] = None,
52
+ service: Optional[str] = None,
53
+ environment: Optional[str] = None,
54
+ release: Optional[str] = None,
55
+ enabled: Optional[bool] = None,
56
+ flush_interval: float = 5.0,
57
+ timeout: float = 2.0,
58
+ logs_level: Optional[str] = "WARNING",
59
+ capture_queries: bool = True,
60
+ capture_http: bool = True,
61
+ capture_redis: bool = True,
62
+ ignore_paths: tuple = ("/health", "/healthz", "/up", "/favicon.ico", "/metrics"),
63
+ health_checks: Optional[Dict[str, Callable]] = None,
64
+ health_interval: float = 60.0,
65
+ root: Optional[str] = None,
66
+ ):
67
+ self.key = key or _env("LOGGERAI_KEY")
68
+ self.endpoint = endpoint or _env("LOGGERAI_ENDPOINT", DEFAULT_ENDPOINT)
69
+ self.service = service or _env("LOGGERAI_SERVICE", "app")
70
+ self.environment = environment or _env("LOGGERAI_ENVIRONMENT") or _env("ENVIRONMENT") or _env("APP_ENV") or "production"
71
+ self.release = release or _env("LOGGERAI_RELEASE")
72
+ on = _truthy(_env("LOGGERAI_ENABLED", "true")) if enabled is None else enabled
73
+ self.enabled = bool(on and self.key and self.key.startswith("sk_"))
74
+ if on and self.key and not self.key.startswith("sk_"):
75
+ log.warning("LoggerAI: servers need the secret key (sk_live_...); the public key is for browsers. Not sending.")
76
+ self.flush_interval = max(1.0, float(flush_interval))
77
+ self.timeout = timeout
78
+ self.logs_level = logs_level
79
+ self.capture_queries, self.capture_http, self.capture_redis = capture_queries, capture_http, capture_redis
80
+ self.ignore_paths = tuple(ignore_paths or ())
81
+ self.health_checks = dict(health_checks or {})
82
+ self.health_interval = health_interval
83
+ self.root = os.path.abspath(root or os.getcwd())
84
+ self.host = socket.gethostname()
85
+
86
+ self._lock = threading.Lock()
87
+ self._buf: Dict[str, List[dict]] = {k: [] for k in KINDS}
88
+ self._wake = threading.Event()
89
+ self._idle = threading.Event()
90
+ self._idle.set()
91
+ self._thread: Optional[threading.Thread] = None
92
+ self._pid = os.getpid()
93
+ self._stopped = False
94
+ self._next_health = 0.0
95
+ self.last_error: Optional[str] = None
96
+
97
+ # ---- recording ------------------------------------------------------------------
98
+
99
+ def ignored(self, path: str) -> bool:
100
+ return any(path == p or path.startswith(p.rstrip("/") + "/") for p in self.ignore_paths)
101
+
102
+ def add(self, kind: str, record: dict) -> None:
103
+ if not self.enabled:
104
+ return
105
+ with self._lock:
106
+ buf = self._buf[kind]
107
+ buf.append(record)
108
+ if len(buf) > MAX_BUFFER:
109
+ del buf[: len(buf) - MAX_BUFFER]
110
+ self._ensure_thread()
111
+
112
+ def finish(self, unit: context.Unit, status: int) -> None:
113
+ self.add("requests", unit.record(status))
114
+
115
+ def exception(self, exc: BaseException, status: Optional[int] = None, handled: bool = False, extra: Optional[dict] = None) -> None:
116
+ if not self.enabled or getattr(exc, "__loggerai_seen__", False):
117
+ return
118
+ try:
119
+ exc.__loggerai_seen__ = True # reported once, however many layers see it
120
+ except Exception:
121
+ pass
122
+ unit = context.current.get()
123
+ self.add("errors", {
124
+ "ts": round(time.time(), 3),
125
+ "type": type_name(exc),
126
+ "message": redact_string(str(exc)[:1000]),
127
+ "handled": handled,
128
+ "route": unit.route if unit else None,
129
+ "method": unit.method if unit else None,
130
+ "status": status,
131
+ "trace_id": unit.trace_id if unit else None,
132
+ "frames": frames(exc, self.root),
133
+ "context": redact(extra) if extra else {},
134
+ })
135
+
136
+ def log(self, level: str, logger: str, message: str) -> None:
137
+ unit = context.current.get()
138
+ self.add("logs", {
139
+ "ts": round(time.time(), 3), "level": level, "logger": logger[:120], "message": redact_string(message[:8000]),
140
+ "route": unit.route if unit else None, "trace_id": unit.trace_id if unit else None,
141
+ })
142
+
143
+ def user_ref(self, user_id) -> Optional[str]:
144
+ """An opaque, stable id for a user: never the id itself, never an email."""
145
+ if user_id in (None, ""):
146
+ return None
147
+ return hmac.new((self.key or "").encode(), str(user_id).encode(), hashlib.sha256).hexdigest()[:16]
148
+
149
+ # ---- sending ---------------------------------------------------------------------
150
+
151
+ def _ensure_thread(self) -> None:
152
+ if self._pid != os.getpid(): # forked (gunicorn, uWSGI, Celery): the parent's thread didn't come along
153
+ self._pid = os.getpid()
154
+ self._thread = None
155
+ with self._lock:
156
+ self._buf = {k: [] for k in KINDS}
157
+ if self._thread is None and not self._stopped:
158
+ self._thread = threading.Thread(target=self._run, name="loggerai", daemon=True)
159
+ self._thread.start()
160
+
161
+ def start(self) -> None:
162
+ """Starts the sender now (for health checks on a quiet app)."""
163
+ if self.enabled:
164
+ self._ensure_thread()
165
+
166
+ def _run(self) -> None:
167
+ while not self._stopped:
168
+ self._wake.wait(self.flush_interval)
169
+ self._wake.clear()
170
+ self._idle.clear()
171
+ try:
172
+ self._run_health()
173
+ self._send_all()
174
+ except Exception as e: # never let the thread die
175
+ log.debug("LoggerAI: send failed: %s", e)
176
+ finally:
177
+ self._idle.set()
178
+
179
+ def _run_health(self) -> None:
180
+ if not self.health_checks or time.monotonic() < self._next_health:
181
+ return
182
+ self._next_health = time.monotonic() + self.health_interval
183
+ for name, fn in self.health_checks.items():
184
+ t = time.perf_counter()
185
+ try:
186
+ r = fn()
187
+ ok, detail = (r if isinstance(r, tuple) else (r is not False, None))
188
+ except Exception as e:
189
+ ok, detail = False, f"{type(e).__name__}: {e}"[:255]
190
+ self.add("checks", {"ts": round(time.time(), 3), "name": name, "ok": bool(ok),
191
+ "ms": round((time.perf_counter() - t) * 1000, 2), "detail": detail})
192
+
193
+ def _drain(self) -> Dict[str, List[dict]]:
194
+ with self._lock:
195
+ out = {k: v[:MAX_PER_BATCH] for k, v in self._buf.items() if v}
196
+ for k in out:
197
+ del self._buf[k][: len(out[k])]
198
+ return out
199
+
200
+ def _send_all(self) -> None:
201
+ for _ in range(20): # a burst goes out in several batches, then waits for the next tick
202
+ parts = self._drain()
203
+ if not parts or not self.enabled:
204
+ return
205
+ self._post(parts)
206
+
207
+ def _post(self, parts: Dict[str, List[dict]]) -> None:
208
+ body = json.dumps({
209
+ "sdk": {"name": "loggerai-python", "version": __version__},
210
+ "service": self.service, "environment": self.environment, "release": self.release, "host": self.host,
211
+ **parts,
212
+ }, separators=(",", ":"), default=str).encode()
213
+ if len(body) > MAX_BATCH_BYTES and sum(len(v) for v in parts.values()) > 1:
214
+ for half in _halves(parts):
215
+ self._post(half)
216
+ return
217
+ req = urllib.request.Request(self.endpoint, data=gzip.compress(body), method="POST", headers={
218
+ "Content-Type": "application/json", "Content-Encoding": "gzip", "X-LoggerAI-Key": self.key or "",
219
+ "User-Agent": f"loggerai-python/{__version__}"})
220
+ try:
221
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
222
+ r.read()
223
+ self.last_error = None
224
+ except urllib.error.HTTPError as e:
225
+ self.last_error = f"LoggerAI answered {e.code}"
226
+ if e.code == 401:
227
+ self.enabled = False # a wrong or revoked key won't start working by retrying
228
+ log.warning("LoggerAI: the key was refused (401). Check LOGGERAI_KEY; sending stopped.")
229
+ elif e.code not in (429,) and e.code < 500:
230
+ log.warning("LoggerAI: batch rejected (%s)", e.code)
231
+ except Exception as e:
232
+ self.last_error = f"couldn't reach LoggerAI: {type(e).__name__}"
233
+ log.debug("LoggerAI: %s", self.last_error)
234
+
235
+ def flush(self, timeout: float = 5.0) -> bool:
236
+ """Sends everything recorded so far. True when the buffer is empty."""
237
+ if not self.enabled:
238
+ return True
239
+ if self._thread is None or self._pid != os.getpid():
240
+ self._send_all() # no sender thread here (e.g. a short script): send in this thread
241
+ return not any(self._buf.values())
242
+ deadline = time.monotonic() + timeout
243
+ while time.monotonic() < deadline:
244
+ self._idle.wait(max(0.0, deadline - time.monotonic()))
245
+ if not any(self._buf.values()):
246
+ return True
247
+ self._wake.set()
248
+ time.sleep(0.05)
249
+ self._idle.wait(max(0.0, deadline - time.monotonic()))
250
+ return not any(self._buf.values())
251
+
252
+ def close(self, timeout: float = 2.0) -> None:
253
+ self.flush(timeout)
254
+ self._stopped = True
255
+ self._wake.set()
256
+
257
+
258
+ def _halves(parts: Dict[str, List[dict]]):
259
+ a, b = {}, {}
260
+ for k, v in parts.items():
261
+ mid = len(v) // 2
262
+ if v[:mid]:
263
+ a[k] = v[:mid]
264
+ if v[mid:]:
265
+ b[k] = v[mid:]
266
+ return [x for x in (a, b) if x]
267
+
268
+
269
+ _client: Optional[Client] = None
270
+
271
+
272
+ def get_client() -> Optional[Client]:
273
+ return _client
274
+
275
+
276
+ def set_client(c: Optional[Client]) -> None:
277
+ global _client
278
+ _client = c
279
+
280
+
281
+ @atexit.register
282
+ def _at_exit() -> None:
283
+ if _client is not None:
284
+ _client.close(timeout=2.0)
loggerai/context.py ADDED
@@ -0,0 +1,79 @@
1
+ """The unit of work in progress (an HTTP request, a job, a command): what it
2
+ waited on, grouped by target and operation, until it finishes.
3
+
4
+ Kept in a ContextVar, so it follows the request into async code and into the
5
+ thread pools frameworks run sync code in."""
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import re
10
+ import time
11
+ from contextvars import ContextVar
12
+ from typing import Dict, Optional
13
+
14
+ _TRACEPARENT = re.compile(r"^[0-9a-f]{2}-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$")
15
+
16
+
17
+ class Unit:
18
+ __slots__ = ("kind", "method", "route", "trace_id", "session_id", "user", "ts", "started", "deps")
19
+
20
+ def __init__(self, kind: str, method: str, trace_id: Optional[str] = None, session_id: Optional[str] = None):
21
+ self.kind = kind
22
+ self.method = method
23
+ self.route: Optional[str] = None
24
+ self.trace_id = trace_id or os.urandom(16).hex()
25
+ self.session_id = session_id
26
+ self.user: Optional[str] = None
27
+ self.ts = time.time()
28
+ self.started = time.perf_counter()
29
+ self.deps: Dict[tuple, list] = {}
30
+
31
+ def dep(self, target: str, op: str, ms: float, ok: bool = True) -> None:
32
+ d = self.deps.get((target, op))
33
+ if d is None:
34
+ d = self.deps[(target, op)] = [0, 0.0, 0]
35
+ d[0] += 1
36
+ d[1] += ms
37
+ if not ok:
38
+ d[2] += 1
39
+
40
+ def record(self, status: int) -> dict:
41
+ return {
42
+ "ts": round(self.ts, 3),
43
+ "kind": self.kind,
44
+ "method": self.method,
45
+ "route": self.route or "(unmatched)",
46
+ "status": int(status),
47
+ "duration_ms": round((time.perf_counter() - self.started) * 1000, 2),
48
+ "trace_id": self.trace_id,
49
+ "session_id": self.session_id,
50
+ "user": self.user,
51
+ "deps": [{"target": t, "op": o, "count": c, "ms": round(ms, 2), "errors": e} for (t, o), (c, ms, e) in self.deps.items()],
52
+ }
53
+
54
+
55
+ current: ContextVar[Optional[Unit]] = ContextVar("loggerai_unit", default=None)
56
+
57
+
58
+ def trace_from(traceparent: Optional[str]) -> Optional[str]:
59
+ """The trace id from a W3C traceparent header, if it's well formed."""
60
+ m = _TRACEPARENT.match((traceparent or "").strip().lower())
61
+ return m.group(1) if m and m.group(1) != "0" * 32 else None
62
+
63
+
64
+ def session_from(value: Optional[str]) -> Optional[str]:
65
+ v = (value or "").strip()
66
+ return v[:64] if v and re.fullmatch(r"[A-Za-z0-9._:-]+", v) else None
67
+
68
+
69
+ def dependency(target: str, op: str, ms: float, ok: bool = True) -> None:
70
+ """Record a call made during the current unit (ignored outside one)."""
71
+ unit = current.get()
72
+ if unit is not None:
73
+ unit.dep(target, op[:20], ms, ok)
74
+
75
+
76
+ def sql_verb(sql: str) -> str:
77
+ for word in (sql or "").lstrip(" (\n\t").split(None, 1)[:1]:
78
+ return word.upper()[:20]
79
+ return "?"
loggerai/django.py ADDED
@@ -0,0 +1,102 @@
1
+ """Django: call loggerai.init() in settings.py (it reads LOGGERAI_KEY), and add
2
+ the middleware first in MIDDLEWARE:
3
+
4
+ MIDDLEWARE = ["loggerai.django.LoggerAIMiddleware", ...]
5
+
6
+ Queries are timed through Django's own database layer."""
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import time
11
+
12
+ from . import context
13
+ from .client import get_client
14
+
15
+ _CONVERTER = re.compile(r"<(?:[^:<>]+:)?([^<>]+)>")
16
+ _NAMED = re.compile(r"\(\?P<([^>]+)>[^)]*\)")
17
+ _VENDORS = {"postgresql": "postgres", "microsoft": "sqlserver"}
18
+
19
+
20
+ def route_template(resolver_match) -> str | None:
21
+ route = getattr(resolver_match, "route", None)
22
+ if route is None:
23
+ return None
24
+ if route.startswith("^") or route.endswith("$"): # re_path
25
+ route = _NAMED.sub(r"{\1}", route.lstrip("^").rstrip("$"))
26
+ return "/" + _CONVERTER.sub(r"{\1}", route).lstrip("/")
27
+
28
+
29
+ def _db_wrapper(execute, sql, params, many, ctx):
30
+ if context.current.get() is None:
31
+ return execute(sql, params, many, ctx)
32
+ t = time.perf_counter()
33
+ ok = False
34
+ try:
35
+ r = execute(sql, params, many, ctx)
36
+ ok = True
37
+ return r
38
+ finally:
39
+ vendor = ctx["connection"].vendor
40
+ context.dependency(_VENDORS.get(vendor, vendor), context.sql_verb(sql), (time.perf_counter() - t) * 1000, ok)
41
+
42
+
43
+ def _install_db_timing():
44
+ from django.db.backends.signals import connection_created
45
+
46
+ def _on_connect(sender, connection, **kw):
47
+ if _db_wrapper not in connection.execute_wrappers:
48
+ connection.execute_wrappers.append(_db_wrapper)
49
+
50
+ connection_created.connect(_on_connect, weak=False, dispatch_uid="loggerai")
51
+ from django.db import connections
52
+ for conn in connections.all(initialized_only=True) if _has_initialized_only() else []:
53
+ _on_connect(None, conn)
54
+
55
+
56
+ def _has_initialized_only() -> bool:
57
+ import inspect
58
+ from django.db import connections
59
+ return "initialized_only" in inspect.signature(connections.all).parameters
60
+
61
+
62
+ class LoggerAIMiddleware:
63
+ sync_capable = True
64
+ async_capable = False
65
+
66
+ _db_done = False
67
+
68
+ def __init__(self, get_response):
69
+ self.get_response = get_response
70
+ client = get_client()
71
+ if client is not None and client.capture_queries and not LoggerAIMiddleware._db_done:
72
+ LoggerAIMiddleware._db_done = True
73
+ _install_db_timing()
74
+
75
+ def __call__(self, request):
76
+ client = get_client()
77
+ if client is None or not client.enabled or client.ignored(request.path):
78
+ return self.get_response(request)
79
+ unit = context.Unit("http", request.method, context.trace_from(request.META.get("HTTP_TRACEPARENT")),
80
+ context.session_from(request.META.get("HTTP_X_LOGGERAI_SESSION")))
81
+ token = context.current.set(unit)
82
+ status = 500
83
+ try:
84
+ response = self.get_response(request)
85
+ status = response.status_code
86
+ return response
87
+ finally:
88
+ unit.route = route_template(getattr(request, "resolver_match", None)) or unit.route
89
+ user = getattr(request, "user", None)
90
+ if user is not None and getattr(user, "is_authenticated", False):
91
+ unit.user = client.user_ref(getattr(user, "pk", None))
92
+ context.current.reset(token)
93
+ client.finish(unit, status)
94
+
95
+ def process_exception(self, request, exception):
96
+ client = get_client()
97
+ if client is not None:
98
+ unit = context.current.get()
99
+ if unit is not None and unit.route is None:
100
+ unit.route = route_template(getattr(request, "resolver_match", None))
101
+ client.exception(exception, status=500)
102
+ return None
loggerai/flask.py ADDED
@@ -0,0 +1,42 @@
1
+ """Flask:
2
+
3
+ import loggerai, loggerai.flask
4
+ loggerai.init()
5
+ loggerai.flask.instrument(app)
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ from . import context
12
+ from .client import get_client
13
+ from .wsgi import LoggerAIMiddleware
14
+
15
+ _CONVERTER = re.compile(r"<(?:[^:<>]+:)?([^<>]+)>")
16
+
17
+
18
+ def route_template(rule: str) -> str:
19
+ """'/orders/<int:order_id>' -> '/orders/{order_id}'"""
20
+ return _CONVERTER.sub(r"{\1}", rule)
21
+
22
+
23
+ def instrument(app) -> None:
24
+ from flask import got_request_exception, request
25
+
26
+ if getattr(app, "_loggerai", False):
27
+ return
28
+ app._loggerai = True
29
+ app.wsgi_app = LoggerAIMiddleware(app.wsgi_app)
30
+
31
+ @app.before_request
32
+ def _loggerai_route():
33
+ unit = context.current.get()
34
+ if unit is not None and request.url_rule is not None:
35
+ unit.route = route_template(request.url_rule.rule)
36
+
37
+ def _on_exception(sender, exception, **extra):
38
+ client = get_client()
39
+ if client is not None:
40
+ client.exception(exception, status=500)
41
+
42
+ got_request_exception.connect(_on_exception, app, weak=False)
loggerai/frames.py ADDED
@@ -0,0 +1,41 @@
1
+ """Stack frames for an error, innermost first, with the app's own code marked
2
+ (in_app) so LoggerAI groups errors by where they happened in your code."""
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sysconfig
7
+ from typing import List
8
+
9
+ _LIBS = tuple(p for p in {sysconfig.get_paths().get("stdlib"), sysconfig.get_paths().get("platstdlib")} if p)
10
+ _OWN = os.path.dirname(os.path.abspath(__file__))
11
+
12
+
13
+ def _in_app(path: str) -> bool:
14
+ if not path or path.startswith("<"):
15
+ return False
16
+ if "site-packages" in path or "dist-packages" in path or path.startswith(_OWN):
17
+ return False
18
+ return not path.startswith(_LIBS)
19
+
20
+
21
+ def frames(exc: BaseException, root: str, limit: int = 50) -> List[dict]:
22
+ out = []
23
+ tb = exc.__traceback__
24
+ entries = []
25
+ while tb is not None:
26
+ entries.append(tb)
27
+ tb = tb.tb_next
28
+ for tb in reversed(entries[-limit:]): # innermost first
29
+ code = tb.tb_frame.f_code
30
+ path = os.path.abspath(code.co_filename)
31
+ rel = os.path.relpath(path, root) if path.startswith(root + os.sep) else path
32
+ qual = getattr(code, "co_qualname", code.co_name) # 3.11+: Class.method
33
+ cls = qual.rsplit(".", 1)[0] if "." in qual and "<locals>" not in qual else None
34
+ out.append({"file": rel, "line": tb.tb_lineno, "function": code.co_name, "class": cls, "in_app": _in_app(path)})
35
+ return out
36
+
37
+
38
+ def type_name(exc: BaseException) -> str:
39
+ t = type(exc)
40
+ mod = t.__module__
41
+ return t.__qualname__ if mod in ("builtins", "__main__") else f"{mod}.{t.__qualname__}"
loggerai/instrument.py ADDED
@@ -0,0 +1,215 @@
1
+ """Times what a request waits on, for whichever libraries are installed:
2
+ SQLAlchemy (any database), httpx and requests (outgoing HTTP), redis-py. And
3
+ a logging handler for warnings and above. Each is patched once and costs
4
+ nothing outside a request."""
5
+ from __future__ import annotations
6
+
7
+ import logging
8
+ import time
9
+ from urllib.parse import urlsplit
10
+
11
+ from . import context
12
+ from .client import get_client
13
+
14
+ _done = set()
15
+ _DIALECTS = {"postgresql": "postgres", "mssql": "sqlserver"}
16
+
17
+
18
+ def _once(name: str) -> bool:
19
+ if name in _done:
20
+ return False
21
+ _done.add(name)
22
+ return True
23
+
24
+
25
+ def sqlalchemy() -> None:
26
+ try:
27
+ from sqlalchemy import event
28
+ from sqlalchemy.engine import Engine
29
+ except ImportError:
30
+ return
31
+ if not _once("sqlalchemy"):
32
+ return
33
+
34
+ @event.listens_for(Engine, "before_cursor_execute")
35
+ def _before(conn, cursor, statement, params, ctx, many):
36
+ conn.info.setdefault("loggerai_t", []).append(time.perf_counter())
37
+
38
+ @event.listens_for(Engine, "after_cursor_execute")
39
+ def _after(conn, cursor, statement, params, ctx, many):
40
+ stack = conn.info.get("loggerai_t")
41
+ if stack:
42
+ ms = (time.perf_counter() - stack.pop()) * 1000
43
+ name = conn.engine.dialect.name
44
+ context.dependency(_DIALECTS.get(name, name), context.sql_verb(statement), ms)
45
+
46
+ @event.listens_for(Engine, "handle_error")
47
+ def _error(exc_ctx):
48
+ conn = exc_ctx.connection
49
+ stack = conn.info.get("loggerai_t") if conn is not None else None
50
+ if stack:
51
+ ms = (time.perf_counter() - stack.pop()) * 1000
52
+ name = conn.engine.dialect.name
53
+ context.dependency(_DIALECTS.get(name, name), context.sql_verb(exc_ctx.statement or ""), ms, ok=False)
54
+
55
+
56
+ def _host(url) -> str:
57
+ try:
58
+ return urlsplit(str(url)).hostname or "unknown"
59
+ except ValueError:
60
+ return "unknown"
61
+
62
+
63
+ def httpx() -> None:
64
+ try:
65
+ import httpx as _httpx
66
+ except ImportError:
67
+ return
68
+ if not _once("httpx"):
69
+ return
70
+ send, asend = _httpx.Client.send, _httpx.AsyncClient.send
71
+
72
+ def _send(self, request, *a, **kw):
73
+ if context.current.get() is None:
74
+ return send(self, request, *a, **kw)
75
+ t = time.perf_counter()
76
+ ok = False
77
+ try:
78
+ r = send(self, request, *a, **kw)
79
+ ok = r.status_code < 500
80
+ return r
81
+ finally:
82
+ context.dependency(_host(request.url), request.method, (time.perf_counter() - t) * 1000, ok)
83
+
84
+ async def _asend(self, request, *a, **kw):
85
+ if context.current.get() is None:
86
+ return await asend(self, request, *a, **kw)
87
+ t = time.perf_counter()
88
+ ok = False
89
+ try:
90
+ r = await asend(self, request, *a, **kw)
91
+ ok = r.status_code < 500
92
+ return r
93
+ finally:
94
+ context.dependency(_host(request.url), request.method, (time.perf_counter() - t) * 1000, ok)
95
+
96
+ _httpx.Client.send, _httpx.AsyncClient.send = _send, _asend
97
+
98
+
99
+ def requests() -> None:
100
+ try:
101
+ import requests as _requests
102
+ except ImportError:
103
+ return
104
+ if not _once("requests"):
105
+ return
106
+ send = _requests.Session.send
107
+
108
+ def _send(self, request, **kw):
109
+ if context.current.get() is None:
110
+ return send(self, request, **kw)
111
+ t = time.perf_counter()
112
+ ok = False
113
+ try:
114
+ r = send(self, request, **kw)
115
+ ok = r.status_code < 500
116
+ return r
117
+ finally:
118
+ context.dependency(_host(request.url), request.method or "GET", (time.perf_counter() - t) * 1000, ok)
119
+
120
+ _requests.Session.send = _send
121
+
122
+
123
+ def redis() -> None:
124
+ try:
125
+ import redis as _redis
126
+ except ImportError:
127
+ return
128
+ if not _once("redis"):
129
+ return
130
+
131
+ def wrap(cls, name, op=None):
132
+ orig = getattr(cls, name, None)
133
+ if orig is None:
134
+ return
135
+
136
+ def sync(self, *args, **kw):
137
+ if context.current.get() is None:
138
+ return orig(self, *args, **kw)
139
+ t = time.perf_counter()
140
+ ok = False
141
+ try:
142
+ r = orig(self, *args, **kw)
143
+ ok = True
144
+ return r
145
+ finally:
146
+ context.dependency("redis", op or str(args[0] if args else "?").upper(), (time.perf_counter() - t) * 1000, ok)
147
+
148
+ async def asyn(self, *args, **kw):
149
+ if context.current.get() is None:
150
+ return await orig(self, *args, **kw)
151
+ t = time.perf_counter()
152
+ ok = False
153
+ try:
154
+ r = await orig(self, *args, **kw)
155
+ ok = True
156
+ return r
157
+ finally:
158
+ context.dependency("redis", op or str(args[0] if args else "?").upper(), (time.perf_counter() - t) * 1000, ok)
159
+
160
+ import inspect
161
+ setattr(cls, name, asyn if inspect.iscoroutinefunction(orig) else sync)
162
+
163
+ wrap(_redis.Redis, "execute_command")
164
+ wrap(_redis.client.Pipeline, "execute", "PIPELINE")
165
+ try:
166
+ import redis.asyncio as _ar
167
+ wrap(_ar.Redis, "execute_command")
168
+ wrap(_ar.client.Pipeline, "execute", "PIPELINE")
169
+ except ImportError:
170
+ pass
171
+
172
+
173
+ _LEVELS = {"WARNING": "WARNING", "ERROR": "ERROR", "CRITICAL": "CRITICAL", "INFO": "INFO", "DEBUG": "DEBUG"}
174
+
175
+
176
+ class LoggerAIHandler(logging.Handler):
177
+ """Sends log records at or above its level. A record carrying an exception
178
+ is reported as an error with its stack trace instead (once)."""
179
+
180
+ def emit(self, record: logging.LogRecord) -> None:
181
+ if record.name == "loggerai" or record.name.startswith("loggerai."):
182
+ return
183
+ client = get_client()
184
+ if client is None or not client.enabled:
185
+ return
186
+ try:
187
+ if record.exc_info and record.exc_info[1] is not None:
188
+ client.exception(record.exc_info[1], status=None, handled=True, extra={"logger": record.name, "log": record.getMessage()[:500]})
189
+ return
190
+ client.log(_LEVELS.get(record.levelname, "WARNING"), record.name, record.getMessage())
191
+ except Exception:
192
+ pass
193
+
194
+
195
+ def logging_handler(level: str) -> None:
196
+ if not level or not _once("logging"):
197
+ return
198
+ handler = LoggerAIHandler(level=getattr(logging, str(level).upper(), logging.WARNING))
199
+ logging.getLogger().addHandler(handler)
200
+ # uvicorn and gunicorn log errors (with the exception) to their own loggers, which may not reach the root.
201
+ for name in ("uvicorn.error", "gunicorn.error"):
202
+ lg = logging.getLogger(name)
203
+ if not lg.propagate:
204
+ lg.addHandler(handler)
205
+
206
+
207
+ def all_from(client) -> None:
208
+ if client.capture_queries:
209
+ sqlalchemy()
210
+ if client.capture_http:
211
+ httpx()
212
+ requests()
213
+ if client.capture_redis:
214
+ redis()
215
+ logging_handler(client.logs_level)
loggerai/redact.py ADDED
@@ -0,0 +1,99 @@
1
+ """
2
+ Masks secrets before anything leaves the app: by key name (fields, headers,
3
+ query parameters) and by shape (bearer tokens and JWTs anywhere in a string).
4
+ The same rules as LoggerAI's server, browser script and other SDKs.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import re
10
+ from typing import Any
11
+ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
12
+
13
+ MASK = "[REDACTED]"
14
+
15
+ # A key is sensitive when one of its words is one of these
16
+ # ("accessToken" -> access, token; "X-CSRF-Token" -> x, csrf, token).
17
+ _WORDS = {
18
+ "password", "passwd", "pwd", "pass", "passphrase", "secret", "token", "otp", "pin", "cvv", "cvc",
19
+ "ssn", "cookie", "authorization", "auth", "signature", "sig", "credential", "credentials", "bvn", "nin",
20
+ }
21
+ # ...or when its words run together into one of these ("x-api-key" -> xapikey).
22
+ _JOINED = (
23
+ "apikey", "accesskey", "privatekey", "secretkey", "cardnumber", "clientsecret", "sessionid",
24
+ "authtoken", "accesstoken", "refreshtoken", "idtoken", "csrftoken", "xsrf", "setcookie",
25
+ )
26
+ # Query parameters that carry credentials in URLs (e.g. Google's ?key=).
27
+ _URL_EXTRA = {"key", "code", "access_token", "id_token"}
28
+
29
+ _SPLIT = re.compile(r"[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])")
30
+ _JWT = re.compile(r"eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}")
31
+ _BEARER = re.compile(r"(?i)\b(bearer|basic|token)\s+[A-Za-z0-9\-._~+/]{12,}=*")
32
+ _URLISH = re.compile(r"^https?://", re.I)
33
+
34
+
35
+ def is_sensitive(key: Any) -> bool:
36
+ if not isinstance(key, str) or not key:
37
+ return False
38
+ words = [w.lower() for w in _SPLIT.split(key) if w]
39
+ if any(w in _WORDS for w in words):
40
+ return True
41
+ joined = "".join(words)
42
+ return any(j in joined for j in _JOINED)
43
+
44
+
45
+ def redact_string(s: str) -> str:
46
+ s = _JWT.sub("[REDACTED_JWT]", s)
47
+ return _BEARER.sub(lambda m: f"{m.group(1)} {MASK}", s)
48
+
49
+
50
+ def redact_url(url: str) -> str:
51
+ try:
52
+ parts = urlsplit(url)
53
+ except ValueError:
54
+ return redact_string(url)
55
+ if not parts.query:
56
+ return redact_string(url)
57
+ q = [(k, MASK if (is_sensitive(k) or k.lower() in _URL_EXTRA) and v else v) for k, v in parse_qsl(parts.query, keep_blank_values=True)]
58
+ netloc = parts.netloc
59
+ if "@" in netloc: # user:password@host
60
+ netloc = MASK + "@" + netloc.rsplit("@", 1)[1]
61
+ return redact_string(urlunsplit((parts.scheme, netloc, parts.path, urlencode(q, safe="[]/:,"), parts.fragment)))
62
+
63
+
64
+ def _redact_text(s: str) -> str:
65
+ """A string that may itself be JSON, a form body or a URL."""
66
+ t = s.strip()
67
+ if t[:1] in "{[":
68
+ try:
69
+ return json.dumps(redact(json.loads(t)), ensure_ascii=False)
70
+ except (ValueError, RecursionError):
71
+ pass
72
+ if _URLISH.match(t):
73
+ return redact_url(t)
74
+ if "=" in t and " " not in t and len(t) < 20000:
75
+ pairs = parse_qsl(t, keep_blank_values=True)
76
+ if pairs and any(is_sensitive(k) for k, _ in pairs):
77
+ return urlencode([(k, MASK if is_sensitive(k) and v else v) for k, v in pairs], safe="[]")
78
+ return redact_string(s)
79
+
80
+
81
+ def redact(value: Any, _depth: int = 0) -> Any:
82
+ """A copy of value with secrets masked. Safe on any JSON-like data."""
83
+ if _depth > 40:
84
+ return value
85
+ if isinstance(value, dict):
86
+ out = {}
87
+ for k, v in value.items():
88
+ if is_sensitive(k) and v not in (None, "", [], {}):
89
+ out[k] = MASK
90
+ elif isinstance(k, str) and k.lower() in ("url", "href", "referrer", "referer", "location") and isinstance(v, str):
91
+ out[k] = redact_url(v)
92
+ else:
93
+ out[k] = redact(v, _depth + 1)
94
+ return out
95
+ if isinstance(value, list):
96
+ return [redact(v, _depth + 1) for v in value]
97
+ if isinstance(value, str):
98
+ return _redact_text(value) if value else value
99
+ return value
loggerai/wsgi.py ADDED
@@ -0,0 +1,39 @@
1
+ """WSGI middleware for any WSGI app. Flask users: use loggerai.flask.instrument(app),
2
+ which adds route names and exceptions on top of this."""
3
+ from __future__ import annotations
4
+
5
+ from . import context
6
+ from .client import get_client
7
+
8
+
9
+ class LoggerAIMiddleware:
10
+ def __init__(self, app):
11
+ self.app = app
12
+
13
+ def __call__(self, environ, start_response):
14
+ client = get_client()
15
+ if client is None or not client.enabled or client.ignored(environ.get("PATH_INFO", "")):
16
+ return self.app(environ, start_response)
17
+ unit = context.Unit("http", environ.get("REQUEST_METHOD", "GET"), context.trace_from(environ.get("HTTP_TRACEPARENT")),
18
+ context.session_from(environ.get("HTTP_X_LOGGERAI_SESSION")))
19
+ token = context.current.set(unit)
20
+ status = [500]
21
+
22
+ def _start(code, headers, exc_info=None):
23
+ try:
24
+ status[0] = int(str(code).split(" ", 1)[0])
25
+ except ValueError:
26
+ pass
27
+ return start_response(code, headers, exc_info) if exc_info is not None else start_response(code, headers)
28
+
29
+ try:
30
+ body = self.app(environ, _start)
31
+ # Most apps return a list; for streamed bodies the time stops here, before the stream is read.
32
+ return body
33
+ except Exception as e:
34
+ client.exception(e, status=500)
35
+ status[0] = 500
36
+ raise
37
+ finally:
38
+ context.current.reset(token)
39
+ client.finish(unit, status[0])
@@ -0,0 +1,166 @@
1
+ Metadata-Version: 2.5
2
+ Name: loggerai-sdk
3
+ Version: 0.1.0
4
+ Summary: LoggerAI for Python: performance monitoring, errors, logs and health checks for FastAPI, Django, Flask and Celery.
5
+ Project-URL: Homepage, https://loggerai.uk
6
+ Project-URL: Source, https://github.com/ehisakhile/loggerai-python
7
+ Author-email: LoggerAI <dev@loggerai.uk>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: apm,django,errors,fastapi,flask,logging,monitoring,observability
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Framework :: Django
13
+ Classifier: Framework :: FastAPI
14
+ Classifier: Framework :: Flask
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Topic :: System :: Monitoring
19
+ Requires-Python: >=3.8
20
+ Description-Content-Type: text/markdown
21
+
22
+ # LoggerAI for Python
23
+
24
+ Performance monitoring, errors, logs and health checks for FastAPI,
25
+ Starlette, Django, Flask and Celery, with AI that explains what went wrong.
26
+
27
+ - **Every endpoint** timed under its route template (`/orders/{order_id}`):
28
+ p50/p95/p99, Apdex, status codes, slow and failed requests.
29
+ - **What each request waits on**: database queries (SQLAlchemy and Django),
30
+ outgoing HTTP (`httpx`, `requests`), Redis.
31
+ - **Exceptions**, grouped by cause, with stack traces that show your code first.
32
+ - **Logs** at warning and above.
33
+ - **Health checks** you define (database, cache, a queue).
34
+ - **Background work** (Celery tasks, scripts) timed like requests.
35
+ - **Browser sessions** recorded by LoggerAI's browser script link to the
36
+ server request each click caused (`traceparent`, `x-loggerai-session`).
37
+
38
+ The package is `loggerai-sdk`; you import it as `loggerai`.
39
+
40
+ Secrets (passwords, tokens, cookies, API keys, JWTs) are masked before
41
+ anything leaves your server, request and response bodies are never sent, and
42
+ users are counted by a one-way hash of their id. No dependencies; Python 3.8+.
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ pip install loggerai-sdk
48
+ ```
49
+
50
+ Get your project's **secret key** (`sk_live_...`) from LoggerAI → your
51
+ project → **Connect**, and set it in the environment:
52
+
53
+ ```bash
54
+ LOGGERAI_KEY=sk_live_...
55
+ LOGGERAI_RELEASE=$GIT_SHA # optional: "since release X"
56
+ ```
57
+
58
+ Without a key nothing is recorded or sent, so local development stays quiet.
59
+
60
+ ### FastAPI / Starlette
61
+
62
+ ```python
63
+ import loggerai
64
+ from loggerai.asgi import LoggerAIMiddleware
65
+
66
+ loggerai.init()
67
+ app = FastAPI()
68
+ app.add_middleware(LoggerAIMiddleware)
69
+ ```
70
+
71
+ ### Django
72
+
73
+ ```python
74
+ # settings.py
75
+ import loggerai
76
+ loggerai.init()
77
+
78
+ MIDDLEWARE = [
79
+ "loggerai.django.LoggerAIMiddleware", # first
80
+ ...
81
+ ]
82
+ ```
83
+
84
+ ### Flask
85
+
86
+ ```python
87
+ import loggerai, loggerai.flask
88
+
89
+ loggerai.init()
90
+ app = Flask(__name__)
91
+ loggerai.flask.instrument(app)
92
+ ```
93
+
94
+ ### Celery
95
+
96
+ ```python
97
+ import loggerai, loggerai.celery
98
+
99
+ loggerai.init(service="worker")
100
+ loggerai.celery.instrument()
101
+ ```
102
+
103
+ ### Any other WSGI app
104
+
105
+ ```python
106
+ from loggerai.wsgi import LoggerAIMiddleware
107
+ application = LoggerAIMiddleware(application)
108
+ ```
109
+
110
+ ## Health checks
111
+
112
+ ```python
113
+ def database():
114
+ with engine.connect() as c:
115
+ c.execute(text("SELECT 1"))
116
+ return True # or (False, "why")
117
+
118
+ loggerai.init(health_checks={"database": database, "redis": lambda: r.ping()})
119
+ ```
120
+
121
+ They run every minute in the background and show on the project's health
122
+ page; alert on them from the dashboard.
123
+
124
+ ## More
125
+
126
+ ```python
127
+ loggerai.set_user(request.user.id) # only a one-way hash is sent
128
+
129
+ with loggerai.measure("api.stripe.com", "POST"): # calls it can't see itself
130
+ stripe.PaymentIntent.confirm(intent_id)
131
+
132
+ with loggerai.track("job", "send_invoices"): # scripts, cron jobs
133
+ send_invoices()
134
+
135
+ try:
136
+ risky()
137
+ except ValueError as e:
138
+ loggerai.capture_exception(e, order=order.id) # handled, but worth seeing
139
+
140
+ loggerai.flush() # at the end of a short script or a serverless call
141
+ ```
142
+
143
+ ## Settings
144
+
145
+ | Environment | `init()` | Default | |
146
+ |---|---|---|---|
147
+ | `LOGGERAI_KEY` | `key` | — | Secret key; off without it |
148
+ | `LOGGERAI_SERVICE` | `service` | `app` | Name this process (`api`, `worker`) |
149
+ | `LOGGERAI_ENVIRONMENT` | `environment` | `production` | Separates production from staging |
150
+ | `LOGGERAI_RELEASE` | `release` | — | Version or git SHA |
151
+ | `LOGGERAI_ENABLED` | `enabled` | `true` | Turn it off without removing the key |
152
+ | | `logs_level` | `"WARNING"` | Lowest log level sent; `None` for no logs |
153
+ | | `ignore_paths` | `/health`, `/up`, … | Paths not recorded |
154
+ | | `capture_queries`, `capture_http`, `capture_redis` | `True` | |
155
+ | | `flush_interval` | `5` | Seconds between batches |
156
+
157
+ ## How it sends
158
+
159
+ Records are kept in memory and sent from a background thread every few
160
+ seconds, gzipped, with a 2-second timeout. Requests never wait on LoggerAI.
161
+ If it can't be reached, records are dropped instead of piling up. With
162
+ gunicorn or uWSGI, each worker process sends its own batches.
163
+
164
+ ## Support
165
+
166
+ dev@loggerai.uk · https://loggerai.uk
@@ -0,0 +1,16 @@
1
+ loggerai/__init__.py,sha256=8QJqC-RI8rp9FoFJ35x1IkmT0mG5G_GrnV5mzuomhmc,4149
2
+ loggerai/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
3
+ loggerai/asgi.py,sha256=yU8jx5Om5gSebXL4Wg-sskVkfMtCWPuoBaTe6ZXrYoQ,2363
4
+ loggerai/celery.py,sha256=1Y5lHrdMpcfkyxCCw9p9DAg_aJ7s-ap0bSgWOWjmfik,1359
5
+ loggerai/client.py,sha256=RSQInckRooD0eJ6U_68epjXs7H6IBUsaUTJWJw5Utoo,11241
6
+ loggerai/context.py,sha256=wRR3s4t0-dn40fWqNvNhhnDkkMfHY0pDN6-fbQ9g7_Y,2823
7
+ loggerai/django.py,sha256=oxWSijk5E-BXJ-mDfayrWn05f_ybHmQ-gCD2VBnZfd0,3703
8
+ loggerai/flask.py,sha256=e0XOzGrrdu2-yeNpPlIDcEr5HbHet7r2TCjbMwRxTMk,1100
9
+ loggerai/frames.py,sha256=QaiRrWPKlfVZZmC6x8hVjUAbNAOBGWIdc281TIGYFZI,1563
10
+ loggerai/instrument.py,sha256=wX8qOaEhQI8ZOgWLA2xb5K_AUQN-WDtczUp-BT8pY7Y,6936
11
+ loggerai/redact.py,sha256=i_mmpVIQvkxNUqKAEcdDt3Gx6Mm2BUKv-pFVhIovEeo,3855
12
+ loggerai/wsgi.py,sha256=av7gL-fjU0Vl0b095fLbqE0juB7N2l5DyMvGFrr0FEI,1534
13
+ loggerai_sdk-0.1.0.dist-info/METADATA,sha256=t4_m-sZFG9oZHvh7Ph9HthFQUweWimEfIoYRaFW2KzA,4941
14
+ loggerai_sdk-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
15
+ loggerai_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=FhG3gg2wfy8WFL8pwSmIts0IEIsd-YpJkIj4Z8PydjM,1065
16
+ loggerai_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LoggerAI
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.