errorlens 0.2.0__tar.gz → 1.0.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.
Files changed (39) hide show
  1. {errorlens-0.2.0 → errorlens-1.0.0}/.gitignore +2 -0
  2. {errorlens-0.2.0 → errorlens-1.0.0}/LICENSE +1 -1
  3. errorlens-1.0.0/PKG-INFO +159 -0
  4. errorlens-1.0.0/README.md +126 -0
  5. errorlens-1.0.0/pyproject.toml +51 -0
  6. errorlens-1.0.0/src/errorlens/__init__.py +279 -0
  7. errorlens-1.0.0/src/errorlens/_version.py +1 -0
  8. errorlens-1.0.0/src/errorlens/client.py +399 -0
  9. errorlens-1.0.0/src/errorlens/dsn.py +49 -0
  10. errorlens-1.0.0/src/errorlens/integrations/__init__.py +83 -0
  11. errorlens-1.0.0/src/errorlens/integrations/_util.py +41 -0
  12. errorlens-1.0.0/src/errorlens/integrations/asgi.py +77 -0
  13. errorlens-1.0.0/src/errorlens/integrations/celery.py +74 -0
  14. errorlens-1.0.0/src/errorlens/integrations/django.py +95 -0
  15. errorlens-1.0.0/src/errorlens/integrations/excepthook.py +24 -0
  16. errorlens-1.0.0/src/errorlens/integrations/flask.py +59 -0
  17. errorlens-1.0.0/src/errorlens/integrations/httpx.py +75 -0
  18. errorlens-1.0.0/src/errorlens/integrations/logging.py +93 -0
  19. errorlens-1.0.0/src/errorlens/integrations/sqlalchemy.py +39 -0
  20. errorlens-1.0.0/src/errorlens/integrations/starlette.py +45 -0
  21. errorlens-1.0.0/src/errorlens/integrations/stdlib_http.py +83 -0
  22. errorlens-1.0.0/src/errorlens/integrations/threading.py +23 -0
  23. errorlens-1.0.0/src/errorlens/integrations/wsgi.py +168 -0
  24. errorlens-1.0.0/src/errorlens/py.typed +0 -0
  25. errorlens-1.0.0/src/errorlens/scope.py +206 -0
  26. errorlens-1.0.0/src/errorlens/scrub.py +85 -0
  27. errorlens-1.0.0/src/errorlens/serialize.py +71 -0
  28. errorlens-1.0.0/src/errorlens/stacktrace.py +215 -0
  29. errorlens-1.0.0/src/errorlens/tracing.py +251 -0
  30. errorlens-1.0.0/src/errorlens/transport.py +202 -0
  31. errorlens-1.0.0/tests/helpers.py +98 -0
  32. errorlens-1.0.0/tests/test_core.py +225 -0
  33. errorlens-1.0.0/tests/test_integrations.py +351 -0
  34. errorlens-0.2.0/PKG-INFO +0 -60
  35. errorlens-0.2.0/README.md +0 -40
  36. errorlens-0.2.0/pyproject.toml +0 -33
  37. errorlens-0.2.0/src/errorlens/__init__.py +0 -133
  38. errorlens-0.2.0/src/errorlens/_version.py +0 -1
  39. errorlens-0.2.0/tests/test_sdk.py +0 -109
@@ -1,4 +1,6 @@
1
1
  __pycache__/
2
2
  *.egg-info/
3
3
  dist/
4
+ build/
4
5
  .venv/
6
+ .coverage
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 ErrorLens contributors
3
+ Copyright (c) 2026 ErrorLens
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -0,0 +1,159 @@
1
+ Metadata-Version: 2.5
2
+ Name: errorlens
3
+ Version: 1.0.0
4
+ Summary: Python SDK for ErrorLens: error tracking, performance tracing, logs and cron monitoring.
5
+ Project-URL: Homepage, https://errorlens.io
6
+ Project-URL: Documentation, https://errorlens.io/docs/python/
7
+ Project-URL: Source, https://github.com/errorlenshq/errorlens-python
8
+ Project-URL: Issues, https://github.com/errorlenshq/errorlens-python/issues
9
+ Author: ErrorLens
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: apm,error tracking,errorlens,exceptions,logging,monitoring,tracing
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Framework :: Celery
15
+ Classifier: Framework :: Django
16
+ Classifier: Framework :: FastAPI
17
+ Classifier: Framework :: Flask
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.9
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Programming Language :: Python :: 3.13
27
+ Classifier: Programming Language :: Python :: 3.14
28
+ Classifier: Topic :: Software Development :: Bug Tracking
29
+ Classifier: Topic :: System :: Monitoring
30
+ Classifier: Typing :: Typed
31
+ Requires-Python: >=3.9
32
+ Description-Content-Type: text/markdown
33
+
34
+ # ErrorLens for Python
35
+
36
+ Error tracking, performance tracing, logs and cron monitoring for Python apps, reporting to
37
+ [ErrorLens](https://errorlens.io) — the hosted service or your own server.
38
+
39
+ - **No dependencies** — only the Python standard library.
40
+ - **Private by default** — no IP addresses, cookies or request bodies unless you opt in, and passwords,
41
+ tokens and keys are scrubbed before anything leaves your app.
42
+ - **Never in your way** — sending happens on a background thread with a bounded queue; your code never
43
+ waits for the network.
44
+ - **Works with your stack** — Django, Flask, FastAPI/Starlette, Celery, httpx, requests, SQLAlchemy and
45
+ `logging` are instrumented automatically.
46
+ - **Standard tracing** — W3C `traceparent`, so traces connect with OpenTelemetry services too.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pip install errorlens
52
+ ```
53
+
54
+ Python 3.9 or newer.
55
+
56
+ ## Set up
57
+
58
+ ```python
59
+ import errorlens
60
+
61
+ errorlens.init(
62
+ dsn="https://<key>@errorlens.io/<project-id>", # from your project's page
63
+ release="my-app@1.4.2",
64
+ environment="production",
65
+ )
66
+ ```
67
+
68
+ Or set `ERRORLENS_DSN`, `ERRORLENS_RELEASE` and `ERRORLENS_ENVIRONMENT` and call `errorlens.init()`.
69
+ Without a DSN the SDK does nothing, so it's safe in tests and local development.
70
+
71
+ Unhandled exceptions — in the main thread, threads, web requests and Celery tasks — are reported
72
+ automatically.
73
+
74
+ ## Report errors and messages
75
+
76
+ ```python
77
+ try:
78
+ charge(order)
79
+ except PaymentError:
80
+ errorlens.capture_exception()
81
+
82
+ errorlens.capture_message("Payment provider is slow", level="warning")
83
+ ```
84
+
85
+ ## Add context
86
+
87
+ ```python
88
+ errorlens.set_user({"id": "42"})
89
+ errorlens.set_tag("region", "eu-west")
90
+ errorlens.set_context("order", {"id": 9817, "items": 3})
91
+ errorlens.add_breadcrumb(category="payment", message="Charging card")
92
+
93
+ with errorlens.new_scope() as scope: # only for this block
94
+ scope.set_tag("job", "nightly-sync")
95
+ errorlens.capture_exception(err)
96
+ ```
97
+
98
+ Inside web requests and tasks, context is isolated per request automatically.
99
+
100
+ ## Performance
101
+
102
+ ```python
103
+ errorlens.init(dsn="…", traces_sample_rate=0.2) # record 20% of requests
104
+ ```
105
+
106
+ Requests in Django, Flask and FastAPI, their SQL queries and outgoing HTTP calls are timed
107
+ automatically. Time your own work too:
108
+
109
+ ```python
110
+ with errorlens.start_transaction("nightly-export", op="task"):
111
+ with errorlens.start_span("db.query", "load orders"):
112
+ orders = load()
113
+ ```
114
+
115
+ ## Logs
116
+
117
+ ```python
118
+ errorlens.init(dsn="…", enable_logs=True)
119
+
120
+ import logging
121
+ logging.getLogger("checkout").warning("Inventory low for %s", sku) # standard logging
122
+
123
+ errorlens.logger.info("Order {order_id} paid", order_id=42, amount=9.5) # structured
124
+ ```
125
+
126
+ ## Cron monitors
127
+
128
+ ```python
129
+ @errorlens.monitor("nightly-backup", schedule="0 2 * * *")
130
+ def backup():
131
+ ...
132
+ ```
133
+
134
+ ErrorLens alerts you when the job fails, runs too long, or doesn't run at all.
135
+
136
+ ## Options
137
+
138
+ | Option | Default | |
139
+ |---|---|---|
140
+ | `dsn` | `$ERRORLENS_DSN` | Where to send data |
141
+ | `release`, `environment` | env vars / `production` | Shown on every event |
142
+ | `sample_rate` | `1.0` | Share of errors to send |
143
+ | `traces_sample_rate` / `traces_sampler` | off | Performance sampling |
144
+ | `enable_logs` | `False` | Send logs |
145
+ | `send_default_pii` | `False` | Include IP addresses, cookies, request bodies and user details |
146
+ | `scrub_fields` / `safe_fields` | | Extra field names to remove / never remove |
147
+ | `before_send`, `before_send_transaction`, `before_breadcrumb`, `before_send_log` | | Edit or drop data |
148
+ | `ignore_errors` | | Exception types or names never to report |
149
+ | `include_local_variables` | `True` | Local variables in your own frames |
150
+ | `in_app_include` / `in_app_exclude` / `project_root` | | Which frames are your code |
151
+ | `max_breadcrumbs` | `100` | |
152
+ | `trace_propagation_targets` | all | URL patterns that receive `traceparent` |
153
+ | `disabled_integrations` | | e.g. `["sqlalchemy"]` |
154
+
155
+ Full documentation: https://errorlens.io/docs/python/
156
+
157
+ ## License
158
+
159
+ MIT
@@ -0,0 +1,126 @@
1
+ # ErrorLens for Python
2
+
3
+ Error tracking, performance tracing, logs and cron monitoring for Python apps, reporting to
4
+ [ErrorLens](https://errorlens.io) — the hosted service or your own server.
5
+
6
+ - **No dependencies** — only the Python standard library.
7
+ - **Private by default** — no IP addresses, cookies or request bodies unless you opt in, and passwords,
8
+ tokens and keys are scrubbed before anything leaves your app.
9
+ - **Never in your way** — sending happens on a background thread with a bounded queue; your code never
10
+ waits for the network.
11
+ - **Works with your stack** — Django, Flask, FastAPI/Starlette, Celery, httpx, requests, SQLAlchemy and
12
+ `logging` are instrumented automatically.
13
+ - **Standard tracing** — W3C `traceparent`, so traces connect with OpenTelemetry services too.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ pip install errorlens
19
+ ```
20
+
21
+ Python 3.9 or newer.
22
+
23
+ ## Set up
24
+
25
+ ```python
26
+ import errorlens
27
+
28
+ errorlens.init(
29
+ dsn="https://<key>@errorlens.io/<project-id>", # from your project's page
30
+ release="my-app@1.4.2",
31
+ environment="production",
32
+ )
33
+ ```
34
+
35
+ Or set `ERRORLENS_DSN`, `ERRORLENS_RELEASE` and `ERRORLENS_ENVIRONMENT` and call `errorlens.init()`.
36
+ Without a DSN the SDK does nothing, so it's safe in tests and local development.
37
+
38
+ Unhandled exceptions — in the main thread, threads, web requests and Celery tasks — are reported
39
+ automatically.
40
+
41
+ ## Report errors and messages
42
+
43
+ ```python
44
+ try:
45
+ charge(order)
46
+ except PaymentError:
47
+ errorlens.capture_exception()
48
+
49
+ errorlens.capture_message("Payment provider is slow", level="warning")
50
+ ```
51
+
52
+ ## Add context
53
+
54
+ ```python
55
+ errorlens.set_user({"id": "42"})
56
+ errorlens.set_tag("region", "eu-west")
57
+ errorlens.set_context("order", {"id": 9817, "items": 3})
58
+ errorlens.add_breadcrumb(category="payment", message="Charging card")
59
+
60
+ with errorlens.new_scope() as scope: # only for this block
61
+ scope.set_tag("job", "nightly-sync")
62
+ errorlens.capture_exception(err)
63
+ ```
64
+
65
+ Inside web requests and tasks, context is isolated per request automatically.
66
+
67
+ ## Performance
68
+
69
+ ```python
70
+ errorlens.init(dsn="…", traces_sample_rate=0.2) # record 20% of requests
71
+ ```
72
+
73
+ Requests in Django, Flask and FastAPI, their SQL queries and outgoing HTTP calls are timed
74
+ automatically. Time your own work too:
75
+
76
+ ```python
77
+ with errorlens.start_transaction("nightly-export", op="task"):
78
+ with errorlens.start_span("db.query", "load orders"):
79
+ orders = load()
80
+ ```
81
+
82
+ ## Logs
83
+
84
+ ```python
85
+ errorlens.init(dsn="…", enable_logs=True)
86
+
87
+ import logging
88
+ logging.getLogger("checkout").warning("Inventory low for %s", sku) # standard logging
89
+
90
+ errorlens.logger.info("Order {order_id} paid", order_id=42, amount=9.5) # structured
91
+ ```
92
+
93
+ ## Cron monitors
94
+
95
+ ```python
96
+ @errorlens.monitor("nightly-backup", schedule="0 2 * * *")
97
+ def backup():
98
+ ...
99
+ ```
100
+
101
+ ErrorLens alerts you when the job fails, runs too long, or doesn't run at all.
102
+
103
+ ## Options
104
+
105
+ | Option | Default | |
106
+ |---|---|---|
107
+ | `dsn` | `$ERRORLENS_DSN` | Where to send data |
108
+ | `release`, `environment` | env vars / `production` | Shown on every event |
109
+ | `sample_rate` | `1.0` | Share of errors to send |
110
+ | `traces_sample_rate` / `traces_sampler` | off | Performance sampling |
111
+ | `enable_logs` | `False` | Send logs |
112
+ | `send_default_pii` | `False` | Include IP addresses, cookies, request bodies and user details |
113
+ | `scrub_fields` / `safe_fields` | | Extra field names to remove / never remove |
114
+ | `before_send`, `before_send_transaction`, `before_breadcrumb`, `before_send_log` | | Edit or drop data |
115
+ | `ignore_errors` | | Exception types or names never to report |
116
+ | `include_local_variables` | `True` | Local variables in your own frames |
117
+ | `in_app_include` / `in_app_exclude` / `project_root` | | Which frames are your code |
118
+ | `max_breadcrumbs` | `100` | |
119
+ | `trace_propagation_targets` | all | URL patterns that receive `traceparent` |
120
+ | `disabled_integrations` | | e.g. `["sqlalchemy"]` |
121
+
122
+ Full documentation: https://errorlens.io/docs/python/
123
+
124
+ ## License
125
+
126
+ MIT
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "errorlens"
7
+ dynamic = ["version"]
8
+ description = "Python SDK for ErrorLens: error tracking, performance tracing, logs and cron monitoring."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ authors = [{ name = "ErrorLens" }]
14
+ keywords = ["error tracking", "exceptions", "monitoring", "apm", "tracing", "logging", "errorlens"]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Programming Language :: Python :: 3.9",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Programming Language :: Python :: 3.14",
27
+ "Framework :: Django",
28
+ "Framework :: Flask",
29
+ "Framework :: FastAPI",
30
+ "Framework :: Celery",
31
+ "Topic :: Software Development :: Bug Tracking",
32
+ "Topic :: System :: Monitoring",
33
+ "Typing :: Typed",
34
+ ]
35
+ # No dependencies: only the Python standard library.
36
+ dependencies = []
37
+
38
+ [project.urls]
39
+ Homepage = "https://errorlens.io"
40
+ Documentation = "https://errorlens.io/docs/python/"
41
+ Source = "https://github.com/errorlenshq/errorlens-python"
42
+ Issues = "https://github.com/errorlenshq/errorlens-python/issues"
43
+
44
+ [tool.hatch.version]
45
+ path = "src/errorlens/_version.py"
46
+
47
+ [tool.hatch.build.targets.wheel]
48
+ packages = ["src/errorlens"]
49
+
50
+ [tool.hatch.build.targets.sdist]
51
+ include = ["src/errorlens", "tests", "README.md", "LICENSE"]
@@ -0,0 +1,279 @@
1
+ """ErrorLens SDK for Python.
2
+
3
+ import errorlens
4
+
5
+ errorlens.init(dsn="https://<key>@errorlens.io/<project-id>", release="app@1.0.0")
6
+
7
+ Unhandled exceptions are reported automatically; see https://errorlens.io/docs/python/.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import functools
13
+ import inspect
14
+ import logging
15
+ import os
16
+ import time
17
+ import warnings
18
+ from dataclasses import fields
19
+ from typing import Any, Callable, Dict, Optional, TypeVar, Union
20
+
21
+ from . import scope as _scope
22
+ from ._version import __version__
23
+ from .client import Client, Options
24
+ from .scope import Scope, get_current_scope, get_global_scope, get_isolation_scope, isolation_scope, new_scope
25
+ from .tracing import Span, Transaction, current_span, outgoing_traceparent, start_span
26
+
27
+ __all__ = [
28
+ "__version__", "init", "is_enabled", "get_client", "flush", "close",
29
+ "capture_exception", "capture_message", "capture_event", "last_event_id",
30
+ "add_breadcrumb", "set_user", "set_tag", "set_tags", "set_extra", "set_context", "set_level",
31
+ "new_scope", "isolation_scope", "get_current_scope", "get_isolation_scope", "get_global_scope", "Scope",
32
+ "start_transaction", "start_span", "current_span", "get_traceparent", "Span", "Transaction",
33
+ "monitor", "capture_checkin", "logger",
34
+ ]
35
+
36
+ _log = logging.getLogger("errorlens")
37
+ _client: Optional[Client] = None
38
+ _OPTION_NAMES = {f.name for f in fields(Options)}
39
+ F = TypeVar("F", bound=Callable[..., Any])
40
+
41
+
42
+ # --- setup -------------------------------------------------------------------------------------
43
+
44
+
45
+ def init(dsn: Optional[str] = None, **options: Any) -> Client:
46
+ """Start reporting to ErrorLens.
47
+
48
+ dsn, release and environment default to the ERRORLENS_DSN, ERRORLENS_RELEASE and
49
+ ERRORLENS_ENVIRONMENT environment variables. Without a DSN the SDK does nothing,
50
+ so it's safe to call in tests and local development.
51
+ """
52
+ global _client
53
+ if _client is not None:
54
+ _client.close(timeout=1.0)
55
+ unknown = sorted(set(options) - _OPTION_NAMES)
56
+ if unknown:
57
+ warnings.warn(f"errorlens.init: unknown option(s) ignored: {', '.join(unknown)}", stacklevel=2)
58
+ for k in unknown:
59
+ options.pop(k)
60
+ opts = Options(dsn=dsn or os.environ.get("ERRORLENS_DSN") or None, **options)
61
+ if opts.debug:
62
+ logging.getLogger("errorlens").setLevel(logging.DEBUG)
63
+ _scope.configure_breadcrumbs(opts.max_breadcrumbs)
64
+ client = Client(opts)
65
+ _client = client
66
+ if client.active:
67
+ from .integrations import setup_integrations
68
+
69
+ client.integrations = setup_integrations(client)
70
+ elif opts.dsn is None and opts.debug:
71
+ _log.debug("errorlens: no DSN set; reporting is off")
72
+ return client
73
+
74
+
75
+ def get_client() -> Optional[Client]:
76
+ return _client
77
+
78
+
79
+ def is_enabled() -> bool:
80
+ return bool(_client and _client.active)
81
+
82
+
83
+ def flush(timeout: Optional[float] = None) -> bool:
84
+ """Wait until queued events are sent. Call before short scripts exit."""
85
+ return _client.flush(timeout) if _client else True
86
+
87
+
88
+ def close(timeout: Optional[float] = None) -> None:
89
+ global _client
90
+ if _client:
91
+ _client.close(timeout)
92
+ _client = None
93
+
94
+
95
+ # --- capturing ---------------------------------------------------------------------------------
96
+
97
+
98
+ def capture_exception(error: Optional[BaseException] = None, level: str = "error") -> Optional[str]:
99
+ """Report an exception (the one being handled if omitted). Returns the event id."""
100
+ return _client.capture_exception(error, level=level) if _client else None
101
+
102
+
103
+ def capture_message(message: str, level: str = "info") -> Optional[str]:
104
+ return _client.capture_message(message, level) if _client else None
105
+
106
+
107
+ def capture_event(event: Dict[str, Any], hint: Optional[dict] = None) -> Optional[str]:
108
+ return _client.capture_event(dict(event), hint) if _client else None
109
+
110
+
111
+ def last_event_id() -> Optional[str]:
112
+ return _client.last_event_id if _client else None
113
+
114
+
115
+ def add_breadcrumb(crumb: Optional[Dict[str, Any]] = None, hint: Optional[dict] = None, **kwargs: Any) -> None:
116
+ """add_breadcrumb(category="auth", message="User signed in", level="info", data={...})"""
117
+ if _client:
118
+ _client.add_breadcrumb(dict(crumb or {}, **kwargs), hint)
119
+
120
+
121
+ # --- context (applies to the current request or task) --------------------------------------------
122
+
123
+
124
+ def set_user(user: Optional[Dict[str, Any]]) -> None:
125
+ get_isolation_scope().set_user(user)
126
+
127
+
128
+ def set_tag(key: str, value: Any) -> None:
129
+ get_isolation_scope().set_tag(key, value)
130
+
131
+
132
+ def set_tags(tags: Dict[str, Any]) -> None:
133
+ get_isolation_scope().set_tags(tags)
134
+
135
+
136
+ def set_extra(key: str, value: Any) -> None:
137
+ get_isolation_scope().set_extra(key, value)
138
+
139
+
140
+ def set_context(key: str, value: Optional[Dict[str, Any]]) -> None:
141
+ get_isolation_scope().set_context(key, value)
142
+
143
+
144
+ def set_level(level: str) -> None:
145
+ get_isolation_scope().set_level(level)
146
+
147
+
148
+ # --- tracing -----------------------------------------------------------------------------------
149
+
150
+
151
+ def start_transaction(name: str, op: str = "function", traceparent: Optional[str] = None) -> Transaction:
152
+ """A transaction for work no integration covers, e.g. a script or job:
153
+
154
+ with errorlens.start_transaction("nightly-export", op="task"):
155
+ ...
156
+ """
157
+ from .tracing import parse_traceparent
158
+
159
+ parent = parse_traceparent(traceparent)
160
+ if _client is None:
161
+ return Transaction(name, op, None, sampled=False)
162
+ if parent:
163
+ return _client.start_transaction(name, op, parent[0], parent[1], parent[2])
164
+ return _client.start_transaction(name, op)
165
+
166
+
167
+ def get_traceparent() -> Optional[str]:
168
+ """The W3C traceparent header value to propagate the current trace."""
169
+ return outgoing_traceparent()
170
+
171
+
172
+ # --- cron monitors -----------------------------------------------------------------------------
173
+
174
+
175
+ def capture_checkin(monitor_slug: str, status: str, check_in_id: Optional[str] = None,
176
+ duration: Optional[float] = None, monitor_config: Optional[Dict[str, Any]] = None) -> Optional[str]:
177
+ """Report a cron run: status is "in_progress", "ok" or "error"."""
178
+ return _client.capture_checkin(monitor_slug, status, check_in_id, duration, monitor_config) if _client else None
179
+
180
+
181
+ class monitor: # noqa: N801 - used as a decorator and a context manager
182
+ """Report a scheduled job's runs to a cron monitor.
183
+
184
+ @errorlens.monitor("nightly-backup", schedule="0 2 * * *")
185
+ def backup(): ...
186
+
187
+ with errorlens.monitor("sync-inventory"):
188
+ sync()
189
+
190
+ With a schedule, the monitor is created or updated from code.
191
+ """
192
+
193
+ def __init__(self, slug: str, schedule: Optional[str] = None, timezone: str = "UTC",
194
+ checkin_margin: Optional[int] = None, max_runtime: Optional[int] = None):
195
+ self.slug = slug
196
+ self.config: Optional[Dict[str, Any]] = None
197
+ if schedule:
198
+ self.config = {"schedule": {"type": "crontab", "value": schedule}, "timezone": timezone}
199
+ if checkin_margin is not None:
200
+ self.config["checkin_margin"] = checkin_margin
201
+ if max_runtime is not None:
202
+ self.config["max_runtime"] = max_runtime
203
+ self._id: Optional[str] = None
204
+ self._start = 0.0
205
+
206
+ def __enter__(self) -> "monitor":
207
+ self._start = time.monotonic()
208
+ self._id = capture_checkin(self.slug, "in_progress", monitor_config=self.config)
209
+ return self
210
+
211
+ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
212
+ capture_checkin(self.slug, "error" if exc_type else "ok", self._id,
213
+ duration=time.monotonic() - self._start, monitor_config=self.config)
214
+
215
+ def __call__(self, fn: F) -> F:
216
+ if inspect.iscoroutinefunction(fn):
217
+ @functools.wraps(fn)
218
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
219
+ m = monitor(self.slug)
220
+ m.config = self.config
221
+ with m:
222
+ return await fn(*args, **kwargs)
223
+ return async_wrapper # type: ignore[return-value]
224
+
225
+ @functools.wraps(fn)
226
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
227
+ m = monitor(self.slug)
228
+ m.config = self.config
229
+ with m:
230
+ return fn(*args, **kwargs)
231
+ return wrapper # type: ignore[return-value]
232
+
233
+
234
+ # --- structured logs ---------------------------------------------------------------------------
235
+
236
+
237
+ class _Logger:
238
+ """Structured logs sent to ErrorLens (needs init(enable_logs=True)).
239
+
240
+ errorlens.logger.info("Order {order_id} paid", order_id=42, amount=9.5)
241
+
242
+ Keyword arguments fill the template and become searchable attributes.
243
+ Records from Python's standard logging module are sent too.
244
+ """
245
+
246
+ def _log(self, level: str, template: str, kwargs: Dict[str, Any]) -> None:
247
+ if not _client:
248
+ return
249
+ try:
250
+ body = template.format(**kwargs) if kwargs else template
251
+ except (KeyError, IndexError, ValueError):
252
+ body = template
253
+ attrs: Dict[str, Union[str, int, float, bool]] = {"message.template": template} if kwargs else {}
254
+ attrs.update(kwargs)
255
+ _client.capture_log(level, body, attrs)
256
+
257
+ def trace(self, template: str, **kwargs: Any) -> None:
258
+ self._log("trace", template, kwargs)
259
+
260
+ def debug(self, template: str, **kwargs: Any) -> None:
261
+ self._log("debug", template, kwargs)
262
+
263
+ def info(self, template: str, **kwargs: Any) -> None:
264
+ self._log("info", template, kwargs)
265
+
266
+ def warning(self, template: str, **kwargs: Any) -> None:
267
+ self._log("warn", template, kwargs)
268
+
269
+ warn = warning
270
+
271
+ def error(self, template: str, **kwargs: Any) -> None:
272
+ self._log("error", template, kwargs)
273
+
274
+ def fatal(self, template: str, **kwargs: Any) -> None:
275
+ self._log("fatal", template, kwargs)
276
+
277
+
278
+ logger = _Logger()
279
+
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"