zharp 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.
- zharp/__init__.py +298 -0
- zharp/_config.py +161 -0
- zharp/_context.py +154 -0
- zharp/_errors.py +156 -0
- zharp/_setup.py +340 -0
- zharp/_version.py +1 -0
- zharp/py.typed +0 -0
- zharp-0.1.0.dist-info/METADATA +173 -0
- zharp-0.1.0.dist-info/RECORD +12 -0
- zharp-0.1.0.dist-info/WHEEL +5 -0
- zharp-0.1.0.dist-info/licenses/LICENSE +21 -0
- zharp-0.1.0.dist-info/top_level.txt +1 -0
zharp/__init__.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
"""Zharp Application Monitoring for Python.
|
|
2
|
+
|
|
3
|
+
.. code-block:: python
|
|
4
|
+
|
|
5
|
+
import zharp
|
|
6
|
+
|
|
7
|
+
zharp.init(key="zpk_…", service="checkout-api", environment="production")
|
|
8
|
+
|
|
9
|
+
That's all a Django, FastAPI or Flask app needs: requests, outgoing HTTP calls (requests, httpx),
|
|
10
|
+
database queries (psycopg, psycopg2, SQLAlchemy) and ``logging`` records are sent with their
|
|
11
|
+
trace, and errors become Zharp issues. It is a thin layer over the official OpenTelemetry SDK —
|
|
12
|
+
anything you instrument with OpenTelemetry yourself is sent too.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import contextlib
|
|
16
|
+
import logging
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
from typing import Any, Callable, Iterator, Mapping, Optional, TypeVar, Union
|
|
20
|
+
|
|
21
|
+
from opentelemetry import context as otel_context
|
|
22
|
+
from opentelemetry import trace as _trace
|
|
23
|
+
from opentelemetry._logs import LogRecord, SeverityNumber
|
|
24
|
+
|
|
25
|
+
from . import _config, _context, _errors, _setup
|
|
26
|
+
from ._version import __version__
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"__version__",
|
|
30
|
+
"capture_error",
|
|
31
|
+
"clear_user",
|
|
32
|
+
"flush",
|
|
33
|
+
"init",
|
|
34
|
+
"is_active",
|
|
35
|
+
"log",
|
|
36
|
+
"set_tag",
|
|
37
|
+
"set_user",
|
|
38
|
+
"shutdown",
|
|
39
|
+
"start_span",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
T = TypeVar("T")
|
|
43
|
+
|
|
44
|
+
_state: Optional[_setup.State] = None
|
|
45
|
+
_lock = threading.Lock()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def init(
|
|
49
|
+
key: Optional[str] = None,
|
|
50
|
+
service: Optional[str] = None,
|
|
51
|
+
environment: Optional[str] = None,
|
|
52
|
+
release: Optional[str] = None,
|
|
53
|
+
endpoint: Optional[str] = None,
|
|
54
|
+
*,
|
|
55
|
+
sample_rate: Optional[float] = None,
|
|
56
|
+
logging_level: Union[str, int, bool, None] = "env",
|
|
57
|
+
capture_uncaught: bool = True,
|
|
58
|
+
instrument: bool = True,
|
|
59
|
+
tracing: Optional[bool] = None,
|
|
60
|
+
quiet: bool = False,
|
|
61
|
+
_exporters=None,
|
|
62
|
+
_batch: bool = True,
|
|
63
|
+
) -> bool:
|
|
64
|
+
"""Start sending traces, logs and errors to Zharp. Call once, as early as possible — at the
|
|
65
|
+
top of manage.py / wsgi.py / asgi.py, or in the module that creates the FastAPI or Flask app.
|
|
66
|
+
|
|
67
|
+
Anything not passed is read from the environment: ``ZHARP_KEY``, ``ZHARP_SERVICE`` (then
|
|
68
|
+
``OTEL_SERVICE_NAME``), ``ZHARP_ENVIRONMENT``, ``ZHARP_RELEASE``, ``ZHARP_ENDPOINT``,
|
|
69
|
+
``ZHARP_SAMPLE_RATE``, ``ZHARP_LOGGING_LEVEL``, ``ZHARP_TRACING``. ``ZHARP_DISABLED=true`` turns
|
|
70
|
+
it off.
|
|
71
|
+
|
|
72
|
+
:param sample_rate: share of traces kept, 0.0–1.0 (default 1.0). Logs and handled errors are
|
|
73
|
+
always sent.
|
|
74
|
+
:param logging_level: the lowest ``logging`` level sent (default ``"INFO"``); ``False``
|
|
75
|
+
leaves ``logging`` alone.
|
|
76
|
+
:param capture_uncaught: report exceptions that end the program or a thread.
|
|
77
|
+
:param instrument: instrument the supported libraries that are installed.
|
|
78
|
+
:param tracing: ``False`` for logs only: logs, errors, user and tags are sent, no spans are
|
|
79
|
+
recorded, HTTP clients and databases aren't instrumented and nothing is injected into
|
|
80
|
+
outgoing requests. Logs in a request still carry its incoming trace id. Default ``True``
|
|
81
|
+
(``ZHARP_TRACING=false`` in the environment).
|
|
82
|
+
|
|
83
|
+
Returns True when it started. Never raises.
|
|
84
|
+
"""
|
|
85
|
+
global _state
|
|
86
|
+
try:
|
|
87
|
+
with _lock:
|
|
88
|
+
if _state is not None:
|
|
89
|
+
return True
|
|
90
|
+
if _config.disabled_by_env():
|
|
91
|
+
return False
|
|
92
|
+
options = _config.resolve(
|
|
93
|
+
key, service, environment, release, endpoint, sample_rate, logging_level, capture_uncaught, instrument,
|
|
94
|
+
tracing,
|
|
95
|
+
)
|
|
96
|
+
if options is None:
|
|
97
|
+
if not quiet:
|
|
98
|
+
_config.announce("No key — set ZHARP_KEY or pass key= to zharp.init(). Nothing is sent.")
|
|
99
|
+
return False
|
|
100
|
+
_state = _setup.start(options, exporters=_exporters, batch=_batch)
|
|
101
|
+
if options.capture_uncaught:
|
|
102
|
+
_errors.install_uncaught_hooks(_report, flush)
|
|
103
|
+
if not quiet:
|
|
104
|
+
_setup.announce_started(_state)
|
|
105
|
+
return True
|
|
106
|
+
except Exception as error: # never break the app that imports us
|
|
107
|
+
_config.announce("Could not start: {}".format(error))
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def is_active() -> bool:
|
|
112
|
+
return _state is not None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# ─── Logs ──────────────────────────────────────────────────────────────────────
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class _Log:
|
|
119
|
+
"""``zharp.log.info("message", {"order_id": 1})`` — debug, info, warn (warning), error, fatal.
|
|
120
|
+
|
|
121
|
+
Each log carries the active trace and the request's user and session. ``logging`` records are
|
|
122
|
+
sent too; this is for logs you only want in Zharp.
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
def debug(self, message: Any, attributes: Optional[Mapping[str, Any]] = None) -> None:
|
|
126
|
+
_emit(SeverityNumber.DEBUG, "DEBUG", message, attributes)
|
|
127
|
+
|
|
128
|
+
def info(self, message: Any, attributes: Optional[Mapping[str, Any]] = None) -> None:
|
|
129
|
+
_emit(SeverityNumber.INFO, "INFO", message, attributes)
|
|
130
|
+
|
|
131
|
+
def warn(self, message: Any, attributes: Optional[Mapping[str, Any]] = None) -> None:
|
|
132
|
+
_emit(SeverityNumber.WARN, "WARN", message, attributes)
|
|
133
|
+
|
|
134
|
+
warning = warn
|
|
135
|
+
|
|
136
|
+
def error(self, message: Any, attributes: Optional[Mapping[str, Any]] = None) -> None:
|
|
137
|
+
"""An error log. Pass an exception (as the message) to report it as an error, handled."""
|
|
138
|
+
if isinstance(message, BaseException):
|
|
139
|
+
capture_error(message, attributes)
|
|
140
|
+
return
|
|
141
|
+
_emit(SeverityNumber.ERROR, "ERROR", message, attributes)
|
|
142
|
+
|
|
143
|
+
def fatal(self, message: Any, attributes: Optional[Mapping[str, Any]] = None) -> None:
|
|
144
|
+
_emit(SeverityNumber.FATAL, "FATAL", message, attributes)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
log = _Log()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _emit(severity: SeverityNumber, text: str, body: Any, attributes: Optional[Mapping[str, Any]]) -> None:
|
|
151
|
+
state = _state
|
|
152
|
+
if state is None:
|
|
153
|
+
return
|
|
154
|
+
try:
|
|
155
|
+
state.logger.emit(
|
|
156
|
+
LogRecord(
|
|
157
|
+
timestamp=time.time_ns(),
|
|
158
|
+
context=otel_context.get_current(),
|
|
159
|
+
severity_text=text,
|
|
160
|
+
severity_number=severity,
|
|
161
|
+
body=body if isinstance(body, str) else str(body),
|
|
162
|
+
attributes=_context.plain(attributes),
|
|
163
|
+
)
|
|
164
|
+
)
|
|
165
|
+
except Exception:
|
|
166
|
+
pass
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# ─── Errors ────────────────────────────────────────────────────────────────────
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def capture_error(error: BaseException, attributes: Optional[Mapping[str, Any]] = None) -> None:
|
|
173
|
+
"""Report an exception you caught. It becomes a Zharp issue (marked handled), with the trace,
|
|
174
|
+
user and session of the current request.
|
|
175
|
+
|
|
176
|
+
.. code-block:: python
|
|
177
|
+
|
|
178
|
+
try:
|
|
179
|
+
charge(order)
|
|
180
|
+
except PaymentError as e:
|
|
181
|
+
zharp.capture_error(e, {"order_id": order.id})
|
|
182
|
+
"""
|
|
183
|
+
_report(error, handled=True, attributes=attributes)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _report(
|
|
187
|
+
error: BaseException,
|
|
188
|
+
handled: bool,
|
|
189
|
+
attributes: Optional[Mapping[str, Any]] = None,
|
|
190
|
+
fatal: bool = False,
|
|
191
|
+
) -> None:
|
|
192
|
+
state = _state
|
|
193
|
+
if state is None or error is None:
|
|
194
|
+
return
|
|
195
|
+
try:
|
|
196
|
+
_errors.mark_reported(error)
|
|
197
|
+
attrs = _context.plain(attributes)
|
|
198
|
+
attrs.update(_errors.exception_attributes(error, handled))
|
|
199
|
+
state.logger.emit(
|
|
200
|
+
LogRecord(
|
|
201
|
+
timestamp=time.time_ns(),
|
|
202
|
+
context=otel_context.get_current(),
|
|
203
|
+
severity_text="FATAL" if fatal else "ERROR",
|
|
204
|
+
severity_number=SeverityNumber.FATAL if fatal else SeverityNumber.ERROR,
|
|
205
|
+
body="{}: {}".format(attrs["exception.type"], error) if str(error) else attrs["exception.type"],
|
|
206
|
+
attributes=attrs,
|
|
207
|
+
)
|
|
208
|
+
)
|
|
209
|
+
except Exception:
|
|
210
|
+
pass
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
# ─── Context ───────────────────────────────────────────────────────────────────
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def set_user(id: Optional[Union[str, int]] = None, email: Optional[str] = None, name: Optional[str] = None) -> None:
|
|
217
|
+
"""The user of the current request (``enduser.id``), on its spans, logs and errors from here
|
|
218
|
+
on. Outside a request it applies to everything after. A browser or mobile app using a Zharp SDK
|
|
219
|
+
already sends its user with each request, so this is only needed when the server knows better.
|
|
220
|
+
"""
|
|
221
|
+
try:
|
|
222
|
+
_context.set_user(None if id is None else str(id), email, name)
|
|
223
|
+
except Exception:
|
|
224
|
+
pass
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def clear_user() -> None:
|
|
228
|
+
try:
|
|
229
|
+
_context.clear_user()
|
|
230
|
+
except Exception:
|
|
231
|
+
pass
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def set_tag(key: str, value: Any) -> None:
|
|
235
|
+
"""An attribute on every span and log from now on (``None`` removes it)."""
|
|
236
|
+
try:
|
|
237
|
+
_context.set_tag(key, value)
|
|
238
|
+
except Exception:
|
|
239
|
+
pass
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
# ─── Spans ─────────────────────────────────────────────────────────────────────
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
@contextlib.contextmanager
|
|
246
|
+
def _span(name: str, attributes: Optional[Mapping[str, Any]]) -> Iterator[Any]:
|
|
247
|
+
tracer = _state.tracer if _state is not None else _trace.get_tracer("zharp", __version__)
|
|
248
|
+
with tracer.start_as_current_span(name, attributes=_context.plain(attributes)) as span:
|
|
249
|
+
yield span
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def start_span(name: str, fn: Optional[Callable[[], T]] = None, attributes: Optional[Mapping[str, Any]] = None):
|
|
253
|
+
"""A span around some work: ``with zharp.start_span("render invoice"):`` or
|
|
254
|
+
``zharp.start_span("render invoice", lambda: render(invoice))``. An exception that escapes is
|
|
255
|
+
recorded on the span and re-raised. With ``tracing=False`` the work runs without a span."""
|
|
256
|
+
if fn is None:
|
|
257
|
+
return _span(name, attributes)
|
|
258
|
+
with _span(name, attributes):
|
|
259
|
+
return fn()
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
# ─── Sending ───────────────────────────────────────────────────────────────────
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def flush(timeout: float = 5.0) -> bool:
|
|
266
|
+
"""Send everything queued now and wait up to ``timeout`` seconds — at the end of a script, a
|
|
267
|
+
job or a serverless function. True when it all went."""
|
|
268
|
+
state = _state
|
|
269
|
+
if state is None:
|
|
270
|
+
return True
|
|
271
|
+
millis = int(timeout * 1000)
|
|
272
|
+
ok = True
|
|
273
|
+
for provider in (state.tracer_provider, state.logger_provider):
|
|
274
|
+
if provider is None:
|
|
275
|
+
continue
|
|
276
|
+
try:
|
|
277
|
+
ok = bool(provider.force_flush(millis)) and ok
|
|
278
|
+
except Exception:
|
|
279
|
+
ok = False
|
|
280
|
+
return ok
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def shutdown() -> None:
|
|
284
|
+
"""Send what's left and stop. Runs by itself when the program exits."""
|
|
285
|
+
global _state
|
|
286
|
+
state = _state
|
|
287
|
+
_state = None
|
|
288
|
+
if state is None:
|
|
289
|
+
return
|
|
290
|
+
for provider in (state.tracer_provider, state.logger_provider):
|
|
291
|
+
if provider is None:
|
|
292
|
+
continue
|
|
293
|
+
try:
|
|
294
|
+
provider.shutdown()
|
|
295
|
+
except Exception:
|
|
296
|
+
pass
|
|
297
|
+
if state.handler is not None:
|
|
298
|
+
logging.getLogger().removeHandler(state.handler)
|
zharp/_config.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Options from init() and the environment, and the startup line."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import sys
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp"
|
|
10
|
+
|
|
11
|
+
_TRUE = re.compile(r"^(true|1|yes|on)$", re.IGNORECASE)
|
|
12
|
+
_FALSE = re.compile(r"^(false|0|no|off|none)$", re.IGNORECASE)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Options:
|
|
17
|
+
key: str
|
|
18
|
+
service: str
|
|
19
|
+
environment: Optional[str]
|
|
20
|
+
release: Optional[str]
|
|
21
|
+
endpoint: str
|
|
22
|
+
sample_rate: float
|
|
23
|
+
#: The lowest ``logging`` level sent; None leaves ``logging`` alone.
|
|
24
|
+
logging_level: Optional[int]
|
|
25
|
+
capture_uncaught: bool
|
|
26
|
+
instrument: bool
|
|
27
|
+
#: False: logs only — no spans, no client/database instrumentation, nothing injected.
|
|
28
|
+
tracing: bool = True
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def env_value(name: str) -> Optional[str]:
|
|
32
|
+
"""An environment variable; None when unset or blank."""
|
|
33
|
+
value = os.environ.get(name)
|
|
34
|
+
if value is None:
|
|
35
|
+
return None
|
|
36
|
+
value = value.strip()
|
|
37
|
+
return value or None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def pick(*values: Optional[str]) -> Optional[str]:
|
|
41
|
+
"""The first value that is non-blank text."""
|
|
42
|
+
for value in values:
|
|
43
|
+
if value is not None and str(value).strip():
|
|
44
|
+
return str(value).strip()
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def flag_of(value: Optional[str]) -> Optional[bool]:
|
|
49
|
+
if value is None:
|
|
50
|
+
return None
|
|
51
|
+
if _TRUE.match(value):
|
|
52
|
+
return True
|
|
53
|
+
if _FALSE.match(value):
|
|
54
|
+
return False
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def disabled_by_env() -> bool:
|
|
59
|
+
"""``ZHARP_DISABLED=true``: start nothing, whatever the code asks for."""
|
|
60
|
+
return flag_of(env_value("ZHARP_DISABLED")) is True
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def project_name() -> Optional[str]:
|
|
64
|
+
"""The app's name from the ``pyproject.toml`` above the script that was started, if any."""
|
|
65
|
+
try:
|
|
66
|
+
start = os.path.abspath(sys.argv[0]) if sys.argv and sys.argv[0] else os.getcwd()
|
|
67
|
+
directory = start if os.path.isdir(start) else os.path.dirname(start)
|
|
68
|
+
for _ in range(8):
|
|
69
|
+
candidate = os.path.join(directory, "pyproject.toml")
|
|
70
|
+
if os.path.isfile(candidate):
|
|
71
|
+
with open(candidate, encoding="utf-8") as f:
|
|
72
|
+
text = f.read()
|
|
73
|
+
section = re.search(r"^\[(project|tool\.poetry)\]\s*$(.*?)(?=^\[|\Z)", text, re.M | re.S)
|
|
74
|
+
if section:
|
|
75
|
+
match = re.search(r"^name\s*=\s*[\"']([^\"']+)[\"']", section.group(2), re.M)
|
|
76
|
+
if match:
|
|
77
|
+
return match.group(1)
|
|
78
|
+
parent = os.path.dirname(directory)
|
|
79
|
+
if parent == directory:
|
|
80
|
+
break
|
|
81
|
+
directory = parent
|
|
82
|
+
except Exception:
|
|
83
|
+
pass
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def logging_level_of(value) -> Optional[int]:
|
|
88
|
+
"""``"INFO"``, ``logging.INFO``, False/"off" (None: leave ``logging`` alone)."""
|
|
89
|
+
import logging
|
|
90
|
+
|
|
91
|
+
if value is None or value is False:
|
|
92
|
+
return None
|
|
93
|
+
if value is True:
|
|
94
|
+
return logging.INFO
|
|
95
|
+
if isinstance(value, int):
|
|
96
|
+
return value
|
|
97
|
+
text = str(value).strip().upper()
|
|
98
|
+
if flag_of(text) is False:
|
|
99
|
+
return None
|
|
100
|
+
level = logging.getLevelName("WARNING" if text == "WARN" else text)
|
|
101
|
+
return level if isinstance(level, int) else logging.INFO
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def resolve(
|
|
105
|
+
key: Optional[str],
|
|
106
|
+
service: Optional[str],
|
|
107
|
+
environment: Optional[str],
|
|
108
|
+
release: Optional[str],
|
|
109
|
+
endpoint: Optional[str],
|
|
110
|
+
sample_rate: Optional[float],
|
|
111
|
+
logging_level,
|
|
112
|
+
capture_uncaught: bool,
|
|
113
|
+
instrument: bool,
|
|
114
|
+
tracing: Optional[bool] = None,
|
|
115
|
+
) -> Optional[Options]:
|
|
116
|
+
"""The options, explicit values first, then ``ZHARP_*``. None when there is no key."""
|
|
117
|
+
resolved_key = pick(key, env_value("ZHARP_KEY"), env_value("ZHARP_API_KEY"))
|
|
118
|
+
if not resolved_key:
|
|
119
|
+
return None
|
|
120
|
+
rate = sample_rate
|
|
121
|
+
if rate is None:
|
|
122
|
+
try:
|
|
123
|
+
rate = float(env_value("ZHARP_SAMPLE_RATE") or 1.0)
|
|
124
|
+
except ValueError:
|
|
125
|
+
rate = 1.0
|
|
126
|
+
if logging_level == "env":
|
|
127
|
+
logging_level = env_value("ZHARP_LOGGING_LEVEL") or "INFO"
|
|
128
|
+
return Options(
|
|
129
|
+
key=resolved_key,
|
|
130
|
+
service=pick(service, env_value("ZHARP_SERVICE"), env_value("OTEL_SERVICE_NAME"), project_name())
|
|
131
|
+
or "unknown-service",
|
|
132
|
+
environment=pick(environment, env_value("ZHARP_ENVIRONMENT"), env_value("ZHARP_ENV")),
|
|
133
|
+
release=pick(release, env_value("ZHARP_RELEASE"), env_value("ZHARP_VERSION")),
|
|
134
|
+
endpoint=(pick(endpoint, env_value("ZHARP_ENDPOINT")) or DEFAULT_ENDPOINT).rstrip("/"),
|
|
135
|
+
sample_rate=min(1.0, max(0.0, rate)),
|
|
136
|
+
logging_level=logging_level_of(logging_level),
|
|
137
|
+
capture_uncaught=capture_uncaught,
|
|
138
|
+
instrument=instrument,
|
|
139
|
+
tracing=tracing_of(tracing),
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def tracing_of(value: Optional[bool]) -> bool:
|
|
144
|
+
"""``tracing=`` when passed, then ``ZHARP_TRACING``; on by default."""
|
|
145
|
+
if value is not None:
|
|
146
|
+
return bool(value)
|
|
147
|
+
return flag_of(env_value("ZHARP_TRACING")) is not False
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def announce(message: str) -> None:
|
|
151
|
+
"""One line on stderr, prefixed so it can be searched for."""
|
|
152
|
+
line = "[Zharp] " + message + "\n"
|
|
153
|
+
try:
|
|
154
|
+
sys.stderr.write(line)
|
|
155
|
+
except UnicodeEncodeError:
|
|
156
|
+
try:
|
|
157
|
+
sys.stderr.write(line.replace("—", "-"))
|
|
158
|
+
except Exception:
|
|
159
|
+
pass
|
|
160
|
+
except Exception:
|
|
161
|
+
pass
|
zharp/_context.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Who and what a span or log belongs to: the user, the session, and tags.
|
|
2
|
+
|
|
3
|
+
A browser or mobile app sends ``enduser.id`` and ``session.id`` in W3C ``baggage`` next to
|
|
4
|
+
``traceparent``. The processors here copy them onto every span and log of that request, so the
|
|
5
|
+
back end's telemetry joins the front end's. ``set_user`` overrides them for the rest of the
|
|
6
|
+
current request (or, outside one, for the rest of the program).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import threading
|
|
10
|
+
from typing import Any, Dict, Mapping, Optional
|
|
11
|
+
|
|
12
|
+
from opentelemetry import baggage, context as otel_context, trace
|
|
13
|
+
from opentelemetry.sdk._logs import LogRecordProcessor
|
|
14
|
+
from opentelemetry.sdk.trace import SpanProcessor
|
|
15
|
+
|
|
16
|
+
USER_ID = "enduser.id"
|
|
17
|
+
USER_EMAIL = "enduser.email"
|
|
18
|
+
USER_NAME = "enduser.name"
|
|
19
|
+
SESSION_ID = "session.id"
|
|
20
|
+
|
|
21
|
+
#: Copied from baggage, and inherited from the parent span when baggage isn't in the context.
|
|
22
|
+
_PROPAGATED = (USER_ID, SESSION_ID)
|
|
23
|
+
_INHERITED = (USER_ID, USER_EMAIL, USER_NAME, SESSION_ID)
|
|
24
|
+
|
|
25
|
+
_USER_KEY = otel_context.create_key("zharp.user")
|
|
26
|
+
|
|
27
|
+
#: Marks a log whose exception was already reported elsewhere; the processor drops its exception.*.
|
|
28
|
+
DUPLICATE_EXCEPTION = "zharp.duplicate_exception"
|
|
29
|
+
#: Set on a logging record by _errors.ExceptionFilter; applied and removed by ContextLogProcessor.
|
|
30
|
+
EXCEPTION_TYPE_OVERRIDE = "zharp.exception_type"
|
|
31
|
+
EXCEPTION_MESSAGE_OVERRIDE = "zharp.exception_message"
|
|
32
|
+
|
|
33
|
+
_tags: Dict[str, Any] = {}
|
|
34
|
+
_tags_lock = threading.Lock()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def set_user(id: Optional[str] = None, email: Optional[str] = None, name: Optional[str] = None) -> None:
|
|
38
|
+
"""Attach a user to the current request (or, outside one, to everything after)."""
|
|
39
|
+
user = {k: str(v) for k, v in ((USER_ID, id), (USER_EMAIL, email), (USER_NAME, name)) if v is not None}
|
|
40
|
+
# Attached without a detach: the instrumentation detaches its own token when the request
|
|
41
|
+
# ends, which drops this with it, so one request's user can't leak into the next.
|
|
42
|
+
otel_context.attach(otel_context.set_value(_USER_KEY, user or None))
|
|
43
|
+
span = trace.get_current_span()
|
|
44
|
+
if user and span.is_recording():
|
|
45
|
+
span.set_attributes(user)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def clear_user() -> None:
|
|
49
|
+
otel_context.attach(otel_context.set_value(_USER_KEY, {}))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def set_tag(key: str, value: Any) -> None:
|
|
53
|
+
"""An attribute on every span and log from now on. None removes it."""
|
|
54
|
+
with _tags_lock:
|
|
55
|
+
if value is None:
|
|
56
|
+
_tags.pop(key, None)
|
|
57
|
+
else:
|
|
58
|
+
_tags[key] = value if isinstance(value, (str, bool, int, float)) else str(value)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def attributes_for(ctx: Optional[otel_context.Context] = None) -> Dict[str, Any]:
|
|
62
|
+
"""The tags, then user and session from the parent span, baggage and set_user (later wins)."""
|
|
63
|
+
ctx = ctx if ctx is not None else otel_context.get_current()
|
|
64
|
+
out: Dict[str, Any] = dict(_tags) if _tags else {}
|
|
65
|
+
|
|
66
|
+
parent = trace.get_current_span(ctx)
|
|
67
|
+
parent_attrs = getattr(parent, "attributes", None)
|
|
68
|
+
if parent_attrs:
|
|
69
|
+
for key in _INHERITED:
|
|
70
|
+
value = parent_attrs.get(key)
|
|
71
|
+
if value:
|
|
72
|
+
out[key] = value
|
|
73
|
+
|
|
74
|
+
for key in _PROPAGATED:
|
|
75
|
+
value = baggage.get_baggage(key, ctx)
|
|
76
|
+
if value:
|
|
77
|
+
out[key] = str(value)
|
|
78
|
+
|
|
79
|
+
user = otel_context.get_value(_USER_KEY, ctx)
|
|
80
|
+
if user is not None:
|
|
81
|
+
for key in (USER_ID, USER_EMAIL, USER_NAME):
|
|
82
|
+
out.pop(key, None)
|
|
83
|
+
out.update(user)
|
|
84
|
+
return out
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class ContextSpanProcessor(SpanProcessor):
|
|
88
|
+
"""Puts user, session and tags on every span as it starts."""
|
|
89
|
+
|
|
90
|
+
def on_start(self, span, parent_context=None) -> None:
|
|
91
|
+
try:
|
|
92
|
+
attrs = attributes_for(parent_context)
|
|
93
|
+
if attrs:
|
|
94
|
+
span.set_attributes(attrs)
|
|
95
|
+
except Exception:
|
|
96
|
+
pass
|
|
97
|
+
|
|
98
|
+
def on_end(self, span) -> None:
|
|
99
|
+
pass
|
|
100
|
+
|
|
101
|
+
def shutdown(self) -> None:
|
|
102
|
+
pass
|
|
103
|
+
|
|
104
|
+
def force_flush(self, timeout_millis: int = 30000) -> bool:
|
|
105
|
+
return True
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class ContextLogProcessor(LogRecordProcessor):
|
|
109
|
+
"""Puts user, session and tags on every log record, before it is batched."""
|
|
110
|
+
|
|
111
|
+
def on_emit(self, log_record) -> None:
|
|
112
|
+
try:
|
|
113
|
+
record = getattr(log_record, "log_record", log_record)
|
|
114
|
+
attributes = record.attributes
|
|
115
|
+
if attributes is None:
|
|
116
|
+
return
|
|
117
|
+
if attributes.get(DUPLICATE_EXCEPTION):
|
|
118
|
+
for key in [k for k in attributes if k.startswith("exception.")] + [DUPLICATE_EXCEPTION, "zharp.handled"]:
|
|
119
|
+
if key in attributes:
|
|
120
|
+
del attributes[key]
|
|
121
|
+
for override, target in ((EXCEPTION_TYPE_OVERRIDE, "exception.type"), (EXCEPTION_MESSAGE_OVERRIDE, "exception.message")):
|
|
122
|
+
if override in attributes:
|
|
123
|
+
if target in attributes or "exception.stacktrace" in attributes:
|
|
124
|
+
attributes[target] = attributes[override]
|
|
125
|
+
del attributes[override]
|
|
126
|
+
for key, value in attributes_for().items():
|
|
127
|
+
if key not in attributes:
|
|
128
|
+
attributes[key] = value
|
|
129
|
+
except Exception:
|
|
130
|
+
pass
|
|
131
|
+
|
|
132
|
+
# Older SDKs call it emit.
|
|
133
|
+
emit = on_emit
|
|
134
|
+
|
|
135
|
+
def shutdown(self) -> None:
|
|
136
|
+
pass
|
|
137
|
+
|
|
138
|
+
def force_flush(self, timeout_millis: int = 30000) -> bool:
|
|
139
|
+
return True
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def plain(attributes: Optional[Mapping[str, Any]]) -> Dict[str, Any]:
|
|
143
|
+
"""User attributes as OTel attribute values: primitives kept, everything else as text."""
|
|
144
|
+
out: Dict[str, Any] = {}
|
|
145
|
+
for key, value in (attributes or {}).items():
|
|
146
|
+
if value is None:
|
|
147
|
+
continue
|
|
148
|
+
if isinstance(value, (str, bool, int, float)):
|
|
149
|
+
out[str(key)] = value
|
|
150
|
+
elif isinstance(value, (list, tuple)) and all(isinstance(v, (str, bool, int, float)) for v in value):
|
|
151
|
+
out[str(key)] = list(value)
|
|
152
|
+
else:
|
|
153
|
+
out[str(key)] = str(value)
|
|
154
|
+
return out
|
zharp/_errors.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Errors: one report per exception, marked handled or not.
|
|
2
|
+
|
|
3
|
+
An exception that escapes a request is seen twice — the instrumentation records it on the request's
|
|
4
|
+
span, and the framework logs it (``django.request``, Flask's app logger, ``uvicorn.error``). Zharp
|
|
5
|
+
turns both into error events, so each exception object is marked when it is first reported and
|
|
6
|
+
later sightings keep their log line or span status but drop the duplicate exception.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
import re
|
|
11
|
+
import sys
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
import traceback
|
|
15
|
+
from typing import Any, Dict, Optional
|
|
16
|
+
|
|
17
|
+
from ._context import DUPLICATE_EXCEPTION, EXCEPTION_MESSAGE_OVERRIDE, EXCEPTION_TYPE_OVERRIDE
|
|
18
|
+
|
|
19
|
+
_MARK = "__zharp_reported__"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
#: Loggers through which frameworks and servers report exceptions that escaped a request.
|
|
23
|
+
_UNCAUGHT_LOGGERS = {
|
|
24
|
+
"django.request",
|
|
25
|
+
"django.server",
|
|
26
|
+
"uvicorn.error",
|
|
27
|
+
"gunicorn.error",
|
|
28
|
+
"hypercorn.error",
|
|
29
|
+
"waitress",
|
|
30
|
+
"tornado.application",
|
|
31
|
+
}
|
|
32
|
+
#: Flask logs "Exception on /path [GET]" through the app's own logger, named after the app.
|
|
33
|
+
_FLASK_UNCAUGHT = re.compile(r"^Exception on \S* \[[A-Z]+\]$")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def is_reported(exc: Optional[BaseException]) -> bool:
|
|
37
|
+
return exc is not None and getattr(exc, _MARK, False) is True
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def mark_reported(exc: Optional[BaseException]) -> None:
|
|
41
|
+
if exc is None:
|
|
42
|
+
return
|
|
43
|
+
try:
|
|
44
|
+
setattr(exc, _MARK, True)
|
|
45
|
+
except Exception:
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def exception_type(exc: BaseException) -> str:
|
|
50
|
+
"""``ValueError``, or ``module.Qualname`` outside builtins — what OTel puts on spans."""
|
|
51
|
+
cls = type(exc)
|
|
52
|
+
module = cls.__module__
|
|
53
|
+
return "{}.{}".format(module, cls.__qualname__) if module and module != "builtins" else cls.__qualname__
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def exception_attributes(exc: BaseException, handled: bool) -> Dict[str, Any]:
|
|
57
|
+
return {
|
|
58
|
+
"exception.type": exception_type(exc),
|
|
59
|
+
"exception.message": str(exc),
|
|
60
|
+
"exception.stacktrace": "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)),
|
|
61
|
+
"zharp.handled": "true" if handled else "false",
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def patch_record_exception() -> None:
|
|
66
|
+
"""Span.record_exception skips an exception already reported, and says handled=false.
|
|
67
|
+
|
|
68
|
+
Instrumentations call it for an exception that escaped their span, which is what an uncaught
|
|
69
|
+
error is; a caller that knows better passes ``{"zharp.handled": "true"}``.
|
|
70
|
+
"""
|
|
71
|
+
from opentelemetry.sdk.trace import Span
|
|
72
|
+
|
|
73
|
+
original = Span.record_exception
|
|
74
|
+
if getattr(original, "_zharp", False):
|
|
75
|
+
return
|
|
76
|
+
|
|
77
|
+
def record_exception(self, exception, attributes=None, timestamp=None, escaped=False):
|
|
78
|
+
if is_reported(exception):
|
|
79
|
+
return None
|
|
80
|
+
mark_reported(exception)
|
|
81
|
+
merged = {"zharp.handled": "false"}
|
|
82
|
+
if attributes:
|
|
83
|
+
merged.update(attributes)
|
|
84
|
+
return original(self, exception, merged, timestamp, escaped)
|
|
85
|
+
|
|
86
|
+
record_exception._zharp = True # type: ignore[attr-defined]
|
|
87
|
+
Span.record_exception = record_exception # type: ignore[method-assign]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class ExceptionFilter(logging.Filter):
|
|
91
|
+
"""On Zharp's logging handler: marks each logged exception, flags repeats, and says whether it
|
|
92
|
+
was caught by the app (handled) or reported by the framework because it escaped (not)."""
|
|
93
|
+
|
|
94
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
95
|
+
name = record.name or ""
|
|
96
|
+
# OTel's own loggers (an exporter that failed) would loop back into the exporter.
|
|
97
|
+
if name.startswith("opentelemetry") or name == "zharp" or name.startswith("zharp."):
|
|
98
|
+
return False
|
|
99
|
+
exc = record.exc_info[1] if record.exc_info else None
|
|
100
|
+
if exc is not None:
|
|
101
|
+
if is_reported(exc):
|
|
102
|
+
record.__dict__[DUPLICATE_EXCEPTION] = True
|
|
103
|
+
else:
|
|
104
|
+
mark_reported(exc)
|
|
105
|
+
# The handler names the type without its module and takes args[0] as the message;
|
|
106
|
+
# the processor puts these back so a log groups with the same error on a span.
|
|
107
|
+
record.__dict__[EXCEPTION_TYPE_OVERRIDE] = exception_type(exc)
|
|
108
|
+
record.__dict__[EXCEPTION_MESSAGE_OVERRIDE] = str(exc)
|
|
109
|
+
uncaught = name in _UNCAUGHT_LOGGERS or bool(_FLASK_UNCAUGHT.match(str(record.msg)))
|
|
110
|
+
record.__dict__.setdefault("zharp.handled", "false" if uncaught else "true")
|
|
111
|
+
return True
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class _Hooks:
|
|
115
|
+
installed = False
|
|
116
|
+
previous_sys = None
|
|
117
|
+
previous_threading = None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def install_uncaught_hooks(report, flush) -> None:
|
|
121
|
+
"""sys.excepthook and threading.excepthook: report (handled=false), send, then the previous hook."""
|
|
122
|
+
if _Hooks.installed:
|
|
123
|
+
return
|
|
124
|
+
_Hooks.installed = True
|
|
125
|
+
_Hooks.previous_sys = sys.excepthook
|
|
126
|
+
|
|
127
|
+
def excepthook(exc_type, exc, tb):
|
|
128
|
+
try:
|
|
129
|
+
if exc is not None and not isinstance(exc, KeyboardInterrupt) and not is_reported(exc):
|
|
130
|
+
report(exc, handled=False, fatal=True)
|
|
131
|
+
flush(2.0)
|
|
132
|
+
except Exception:
|
|
133
|
+
pass
|
|
134
|
+
previous = _Hooks.previous_sys or sys.__excepthook__
|
|
135
|
+
previous(exc_type, exc, tb)
|
|
136
|
+
|
|
137
|
+
sys.excepthook = excepthook
|
|
138
|
+
|
|
139
|
+
if hasattr(threading, "excepthook"):
|
|
140
|
+
_Hooks.previous_threading = threading.excepthook
|
|
141
|
+
|
|
142
|
+
def thread_excepthook(args):
|
|
143
|
+
try:
|
|
144
|
+
exc = args.exc_value
|
|
145
|
+
if exc is not None and not isinstance(exc, SystemExit) and not is_reported(exc):
|
|
146
|
+
report(exc, handled=False, fatal=False)
|
|
147
|
+
except Exception:
|
|
148
|
+
pass
|
|
149
|
+
previous = _Hooks.previous_threading or threading.__excepthook__
|
|
150
|
+
previous(args)
|
|
151
|
+
|
|
152
|
+
threading.excepthook = thread_excepthook
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def now_ns() -> int:
|
|
156
|
+
return time.time_ns()
|
zharp/_setup.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""Wiring the official OpenTelemetry SDK to Zharp: exporters, resource, propagators, the
|
|
2
|
+
``logging`` bridge, the context processors and the instrumentations. No tracer of our own."""
|
|
3
|
+
|
|
4
|
+
import importlib
|
|
5
|
+
import importlib.util
|
|
6
|
+
import logging
|
|
7
|
+
import logging.config
|
|
8
|
+
import os
|
|
9
|
+
import socket
|
|
10
|
+
import threading
|
|
11
|
+
from typing import Callable, List, Optional, Tuple
|
|
12
|
+
|
|
13
|
+
from opentelemetry import propagate, trace
|
|
14
|
+
from opentelemetry._logs import get_logger_provider, set_logger_provider
|
|
15
|
+
from opentelemetry.baggage.propagation import W3CBaggagePropagator
|
|
16
|
+
from opentelemetry.propagators.composite import CompositePropagator
|
|
17
|
+
from opentelemetry.sdk._logs import LoggerProvider
|
|
18
|
+
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
|
19
|
+
from opentelemetry.sdk.resources import Resource
|
|
20
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
21
|
+
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
|
22
|
+
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
|
|
23
|
+
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
|
24
|
+
|
|
25
|
+
from . import _errors
|
|
26
|
+
from ._config import Options, announce
|
|
27
|
+
from ._context import ContextLogProcessor, ContextSpanProcessor
|
|
28
|
+
from ._version import __version__
|
|
29
|
+
|
|
30
|
+
_log = logging.getLogger("zharp")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class State:
|
|
34
|
+
def __init__(self, options: Options, tracer_provider, logger_provider, handler: Optional[logging.Handler]):
|
|
35
|
+
self.options = options
|
|
36
|
+
self.tracer_provider = tracer_provider
|
|
37
|
+
self.logger_provider = logger_provider
|
|
38
|
+
self.handler = handler
|
|
39
|
+
# Logs only: no provider, and zharp.start_span() runs its work without a span.
|
|
40
|
+
self.tracer = (
|
|
41
|
+
tracer_provider.get_tracer("zharp", __version__) if tracer_provider is not None else trace.NoOpTracer()
|
|
42
|
+
)
|
|
43
|
+
self.logger = logger_provider.get_logger("zharp", __version__)
|
|
44
|
+
self.instrumented: List[str] = []
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def resource_for(options: Options) -> Resource:
|
|
48
|
+
attributes = {
|
|
49
|
+
"service.name": options.service,
|
|
50
|
+
"telemetry.sdk.name": "zharp",
|
|
51
|
+
"telemetry.sdk.language": "python",
|
|
52
|
+
"telemetry.sdk.version": __version__,
|
|
53
|
+
"process.pid": os.getpid(),
|
|
54
|
+
}
|
|
55
|
+
if options.release:
|
|
56
|
+
attributes["service.version"] = options.release
|
|
57
|
+
if options.environment:
|
|
58
|
+
attributes["deployment.environment.name"] = options.environment
|
|
59
|
+
try:
|
|
60
|
+
attributes["host.name"] = socket.gethostname()
|
|
61
|
+
except Exception:
|
|
62
|
+
pass
|
|
63
|
+
# Resource.create adds OTEL_RESOURCE_ATTRIBUTES; ours win.
|
|
64
|
+
return Resource.create(attributes)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def default_exporters(options: Options):
|
|
68
|
+
from opentelemetry.exporter.otlp.proto.http import Compression
|
|
69
|
+
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
|
70
|
+
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
|
71
|
+
|
|
72
|
+
headers = {"Authorization": "Bearer " + options.key}
|
|
73
|
+
return (
|
|
74
|
+
OTLPSpanExporter(endpoint=options.endpoint + "/v1/traces", headers=headers, compression=Compression.Gzip),
|
|
75
|
+
OTLPLogExporter(endpoint=options.endpoint + "/v1/logs", headers=headers, compression=Compression.Gzip),
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def start(options: Options, exporters: Optional[Tuple] = None, batch: bool = True) -> State:
|
|
80
|
+
span_exporter, log_exporter = exporters or default_exporters(options)
|
|
81
|
+
resource = resource_for(options)
|
|
82
|
+
|
|
83
|
+
tracer_provider = None
|
|
84
|
+
if options.tracing:
|
|
85
|
+
tracer_provider = _tracer_provider(resource, options)
|
|
86
|
+
tracer_provider.add_span_processor(ContextSpanProcessor())
|
|
87
|
+
tracer_provider.add_span_processor(_span_processor(span_exporter, batch))
|
|
88
|
+
|
|
89
|
+
logger_provider = _logger_provider(resource)
|
|
90
|
+
logger_provider.add_log_record_processor(ContextLogProcessor())
|
|
91
|
+
logger_provider.add_log_record_processor(_log_processor(log_exporter, batch))
|
|
92
|
+
|
|
93
|
+
propagate.set_global_textmap(CompositePropagator([TraceContextTextMapPropagator(), W3CBaggagePropagator()]))
|
|
94
|
+
if options.tracing:
|
|
95
|
+
_errors.patch_record_exception()
|
|
96
|
+
_quiet_repeated_export_errors()
|
|
97
|
+
|
|
98
|
+
handler = None
|
|
99
|
+
if options.logging_level is not None:
|
|
100
|
+
handler = _bridge_logging(logger_provider, options.logging_level)
|
|
101
|
+
|
|
102
|
+
state = State(options, tracer_provider, logger_provider, handler)
|
|
103
|
+
if options.instrument:
|
|
104
|
+
state.instrumented = instrument_installed() if options.tracing else instrument_logs_only()
|
|
105
|
+
return state
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _tracer_provider(resource: Resource, options: Options):
|
|
109
|
+
"""The global SDK provider: ours, or one the app already set (we add our processors to it)."""
|
|
110
|
+
existing = trace.get_tracer_provider()
|
|
111
|
+
if isinstance(existing, TracerProvider):
|
|
112
|
+
return existing
|
|
113
|
+
provider = TracerProvider(resource=resource, sampler=ParentBased(TraceIdRatioBased(options.sample_rate)))
|
|
114
|
+
trace.set_tracer_provider(provider)
|
|
115
|
+
return provider
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _logger_provider(resource: Resource):
|
|
119
|
+
existing = get_logger_provider()
|
|
120
|
+
if isinstance(existing, LoggerProvider):
|
|
121
|
+
return existing
|
|
122
|
+
provider = LoggerProvider(resource=resource)
|
|
123
|
+
set_logger_provider(provider)
|
|
124
|
+
return provider
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _span_processor(exporter, batch: bool):
|
|
128
|
+
if batch:
|
|
129
|
+
return BatchSpanProcessor(exporter, schedule_delay_millis=5000, max_export_batch_size=512)
|
|
130
|
+
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
|
131
|
+
|
|
132
|
+
return SimpleSpanProcessor(exporter)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _log_processor(exporter, batch: bool):
|
|
136
|
+
if batch:
|
|
137
|
+
return BatchLogRecordProcessor(exporter, schedule_delay_millis=5000, max_export_batch_size=512)
|
|
138
|
+
from opentelemetry.sdk._logs.export import SimpleLogRecordProcessor
|
|
139
|
+
|
|
140
|
+
return SimpleLogRecordProcessor(exporter)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# ─── logging ────────────────────────────────────────────────────────────────────
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _handler_class():
|
|
147
|
+
try:
|
|
148
|
+
from opentelemetry.instrumentation.logging.handler import LoggingHandler
|
|
149
|
+
except ImportError: # older releases kept it in the SDK
|
|
150
|
+
import warnings
|
|
151
|
+
|
|
152
|
+
with warnings.catch_warnings():
|
|
153
|
+
warnings.simplefilter("ignore", DeprecationWarning)
|
|
154
|
+
from opentelemetry.sdk._logs import LoggingHandler
|
|
155
|
+
return LoggingHandler
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _bridge_logging(logger_provider, level: int) -> logging.Handler:
|
|
159
|
+
"""OTel's logging handler on the root logger, kept there when the app reconfigures logging."""
|
|
160
|
+
import warnings
|
|
161
|
+
|
|
162
|
+
with warnings.catch_warnings():
|
|
163
|
+
warnings.simplefilter("ignore", DeprecationWarning)
|
|
164
|
+
handler = _handler_class()(level=level, logger_provider=logger_provider)
|
|
165
|
+
handler.addFilter(_errors.ExceptionFilter())
|
|
166
|
+
handler._zharp = True # type: ignore[attr-defined]
|
|
167
|
+
|
|
168
|
+
root = logging.getLogger()
|
|
169
|
+
for existing in list(root.handlers):
|
|
170
|
+
if getattr(existing, "_zharp", False):
|
|
171
|
+
root.removeHandler(existing)
|
|
172
|
+
root.addHandler(handler)
|
|
173
|
+
# The root logger stops at WARNING by default; let the handler see what it asked for.
|
|
174
|
+
if root.level == logging.NOTSET or root.level > level:
|
|
175
|
+
root.setLevel(level)
|
|
176
|
+
|
|
177
|
+
def keep_handler(configure: Callable) -> Callable:
|
|
178
|
+
if getattr(configure, "_zharp", False):
|
|
179
|
+
return configure
|
|
180
|
+
|
|
181
|
+
def wrapper(*args, **kwargs):
|
|
182
|
+
try:
|
|
183
|
+
return configure(*args, **kwargs)
|
|
184
|
+
finally:
|
|
185
|
+
current = logging.getLogger()
|
|
186
|
+
if handler not in current.handlers:
|
|
187
|
+
current.addHandler(handler)
|
|
188
|
+
if current.level == logging.NOTSET or current.level > level:
|
|
189
|
+
current.setLevel(level)
|
|
190
|
+
|
|
191
|
+
wrapper._zharp = True # type: ignore[attr-defined]
|
|
192
|
+
return wrapper
|
|
193
|
+
|
|
194
|
+
logging.config.dictConfig = keep_handler(logging.config.dictConfig)
|
|
195
|
+
logging.config.fileConfig = keep_handler(logging.config.fileConfig)
|
|
196
|
+
logging.basicConfig = keep_handler(logging.basicConfig)
|
|
197
|
+
return handler
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
class _OncePerMessage(logging.Filter):
|
|
201
|
+
"""The exporter logs every failed batch; a wrong key would print one line every 5 seconds."""
|
|
202
|
+
|
|
203
|
+
def __init__(self) -> None:
|
|
204
|
+
super().__init__()
|
|
205
|
+
self._seen = set()
|
|
206
|
+
self._lock = threading.Lock()
|
|
207
|
+
|
|
208
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
209
|
+
key = (record.name, str(record.msg)[:200])
|
|
210
|
+
with self._lock:
|
|
211
|
+
if key in self._seen:
|
|
212
|
+
return False
|
|
213
|
+
if len(self._seen) > 100:
|
|
214
|
+
self._seen.clear()
|
|
215
|
+
self._seen.add(key)
|
|
216
|
+
return True
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _quiet_repeated_export_errors() -> None:
|
|
220
|
+
once = _OncePerMessage()
|
|
221
|
+
for name in (
|
|
222
|
+
"opentelemetry.exporter.otlp.proto.http.trace_exporter",
|
|
223
|
+
"opentelemetry.exporter.otlp.proto.http._log_exporter",
|
|
224
|
+
"opentelemetry.exporter.otlp.proto.http._common",
|
|
225
|
+
"opentelemetry.sdk._shared_internal",
|
|
226
|
+
):
|
|
227
|
+
logging.getLogger(name).addFilter(once)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
# ─── instrumentations ───────────────────────────────────────────────────────────
|
|
231
|
+
|
|
232
|
+
#: (name, library that must be importable, instrumentor module, class)
|
|
233
|
+
INSTRUMENTATIONS = [
|
|
234
|
+
("django", "django", "opentelemetry.instrumentation.django", "DjangoInstrumentor"),
|
|
235
|
+
("fastapi", "fastapi", "opentelemetry.instrumentation.fastapi", "FastAPIInstrumentor"),
|
|
236
|
+
("flask", "flask", "opentelemetry.instrumentation.flask", "FlaskInstrumentor"),
|
|
237
|
+
("requests", "requests", "opentelemetry.instrumentation.requests", "RequestsInstrumentor"),
|
|
238
|
+
("httpx", "httpx", "opentelemetry.instrumentation.httpx", "HTTPXClientInstrumentor"),
|
|
239
|
+
("psycopg", "psycopg", "opentelemetry.instrumentation.psycopg", "PsycopgInstrumentor"),
|
|
240
|
+
("psycopg2", "psycopg2", "opentelemetry.instrumentation.psycopg2", "Psycopg2Instrumentor"),
|
|
241
|
+
("sqlalchemy", "sqlalchemy", "opentelemetry.instrumentation.sqlalchemy", "SQLAlchemyInstrumentor"),
|
|
242
|
+
]
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
#: ASGI's per-message "http send" / "http receive" spans say nothing the request span doesn't.
|
|
246
|
+
_INSTRUMENT_OPTIONS = {"fastapi": {"exclude_spans": ["receive", "send"]}}
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def instrument_installed() -> List[str]:
|
|
250
|
+
"""Instrument every supported library that is installed. Returns their names."""
|
|
251
|
+
done = []
|
|
252
|
+
for name, library, module, cls in INSTRUMENTATIONS:
|
|
253
|
+
try:
|
|
254
|
+
if importlib.util.find_spec(library) is None:
|
|
255
|
+
continue
|
|
256
|
+
if name == "django" and not _django_settings_ready():
|
|
257
|
+
_instrument_django_at_setup(module, cls)
|
|
258
|
+
done.append(name)
|
|
259
|
+
continue
|
|
260
|
+
instrumentor = getattr(importlib.import_module(module), cls)()
|
|
261
|
+
if not instrumentor.is_instrumented_by_opentelemetry:
|
|
262
|
+
instrumentor.instrument(**_INSTRUMENT_OPTIONS.get(name, {}))
|
|
263
|
+
done.append(name)
|
|
264
|
+
except Exception as error: # a missing instrumentation package or a version it rejects
|
|
265
|
+
_log.debug("Zharp: not instrumenting %s: %s", name, error)
|
|
266
|
+
return done
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
#: Logs only: the web frameworks, with a no-op tracer. They still read the incoming ``traceparent``
|
|
270
|
+
#: and ``baggage`` (the request's trace id, user and session go on its logs), but no span is
|
|
271
|
+
#: recorded, and HTTP clients and databases are left alone, so nothing is injected downstream.
|
|
272
|
+
_LOGS_ONLY = ("django", "fastapi", "flask")
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def instrument_logs_only() -> List[str]:
|
|
276
|
+
done = []
|
|
277
|
+
noop = trace.NoOpTracerProvider()
|
|
278
|
+
for name, library, module, cls in INSTRUMENTATIONS:
|
|
279
|
+
if name not in _LOGS_ONLY:
|
|
280
|
+
continue
|
|
281
|
+
try:
|
|
282
|
+
if importlib.util.find_spec(library) is None:
|
|
283
|
+
continue
|
|
284
|
+
kwargs = dict(_INSTRUMENT_OPTIONS.get(name, {}), tracer_provider=noop)
|
|
285
|
+
if name == "django" and not _django_settings_ready():
|
|
286
|
+
_instrument_django_at_setup(module, cls, kwargs)
|
|
287
|
+
done.append(name)
|
|
288
|
+
continue
|
|
289
|
+
instrumentor = getattr(importlib.import_module(module), cls)()
|
|
290
|
+
if not instrumentor.is_instrumented_by_opentelemetry:
|
|
291
|
+
instrumentor.instrument(**kwargs)
|
|
292
|
+
done.append(name)
|
|
293
|
+
except Exception as error:
|
|
294
|
+
_log.debug("Zharp: not instrumenting %s: %s", name, error)
|
|
295
|
+
return done
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _django_settings_ready() -> bool:
|
|
299
|
+
if os.environ.get("DJANGO_SETTINGS_MODULE"):
|
|
300
|
+
return True
|
|
301
|
+
try:
|
|
302
|
+
from django.conf import settings
|
|
303
|
+
|
|
304
|
+
return bool(settings.configured)
|
|
305
|
+
except Exception:
|
|
306
|
+
return False
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _instrument_django_at_setup(module: str, cls: str, kwargs: Optional[dict] = None) -> None:
|
|
310
|
+
"""``zharp.init()`` at the top of manage.py runs before DJANGO_SETTINGS_MODULE is set, and the
|
|
311
|
+
Django instrumentor would configure empty settings. Instrument as django.setup() starts."""
|
|
312
|
+
import django
|
|
313
|
+
|
|
314
|
+
original = django.setup
|
|
315
|
+
if getattr(original, "_zharp", False):
|
|
316
|
+
return
|
|
317
|
+
|
|
318
|
+
def setup(*args, **kwargs):
|
|
319
|
+
django.setup = original
|
|
320
|
+
try:
|
|
321
|
+
instrumentor = getattr(importlib.import_module(module), cls)()
|
|
322
|
+
if not instrumentor.is_instrumented_by_opentelemetry:
|
|
323
|
+
instrumentor.instrument(**(kwargs or {}))
|
|
324
|
+
except Exception as error:
|
|
325
|
+
_log.debug("Zharp: not instrumenting django: %s", error)
|
|
326
|
+
return original(*args, **kwargs)
|
|
327
|
+
|
|
328
|
+
setup._zharp = True # type: ignore[attr-defined]
|
|
329
|
+
django.setup = setup
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def describe(options: Options, instrumented: List[str]) -> str:
|
|
333
|
+
env = 'environment "{}"'.format(options.environment) if options.environment else "no environment set"
|
|
334
|
+
what = ", ".join(instrumented) if instrumented else "no supported libraries found"
|
|
335
|
+
mode = "Application Monitoring active" if options.tracing else "Application Monitoring active, logs only"
|
|
336
|
+
return '{} — service "{}", {} ({})'.format(mode, options.service, env, what)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def announce_started(state: State) -> None:
|
|
340
|
+
announce(describe(state.options, state.instrumented))
|
zharp/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
zharp/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: zharp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zharp Application Monitoring for Python: traces, logs and errors from Django, FastAPI and Flask, on OpenTelemetry.
|
|
5
|
+
Author-email: Zharp <support@zharp.io>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://zharp.io
|
|
8
|
+
Project-URL: Documentation, https://zharp.io/docs/sdks/python
|
|
9
|
+
Project-URL: Source, https://github.com/zharp-io/zharp-python-lib
|
|
10
|
+
Keywords: apm,tracing,opentelemetry,logging,errors,observability,monitoring,zharp
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Framework :: Django
|
|
16
|
+
Classifier: Framework :: FastAPI
|
|
17
|
+
Classifier: Framework :: Flask
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
20
|
+
Classifier: Topic :: System :: Logging
|
|
21
|
+
Classifier: Topic :: System :: Monitoring
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: opentelemetry-api<2,>=1.40
|
|
27
|
+
Requires-Dist: opentelemetry-sdk<2,>=1.40
|
|
28
|
+
Requires-Dist: opentelemetry-exporter-otlp-proto-http<2,>=1.40
|
|
29
|
+
Requires-Dist: opentelemetry-instrumentation>=0.61b0
|
|
30
|
+
Requires-Dist: opentelemetry-instrumentation-logging>=0.61b0
|
|
31
|
+
Requires-Dist: opentelemetry-instrumentation-django>=0.61b0
|
|
32
|
+
Requires-Dist: opentelemetry-instrumentation-fastapi>=0.61b0
|
|
33
|
+
Requires-Dist: opentelemetry-instrumentation-flask>=0.61b0
|
|
34
|
+
Requires-Dist: opentelemetry-instrumentation-requests>=0.61b0
|
|
35
|
+
Requires-Dist: opentelemetry-instrumentation-httpx>=0.61b0
|
|
36
|
+
Requires-Dist: opentelemetry-instrumentation-psycopg>=0.61b0
|
|
37
|
+
Requires-Dist: opentelemetry-instrumentation-psycopg2>=0.61b0
|
|
38
|
+
Requires-Dist: opentelemetry-instrumentation-sqlalchemy>=0.61b0
|
|
39
|
+
Dynamic: license-file
|
|
40
|
+
|
|
41
|
+
# zharp
|
|
42
|
+
|
|
43
|
+
[Zharp](https://zharp.io) Application Monitoring for Python: every request traced, outgoing HTTP
|
|
44
|
+
calls and database queries timed, `logging` records sent with their trace, and errors grouped into
|
|
45
|
+
issues. Built on the official [OpenTelemetry](https://opentelemetry.io) SDK — `zharp` only
|
|
46
|
+
configures it (exporter, resource, propagation, the `logging` bridge) and turns on the
|
|
47
|
+
instrumentations for the libraries you have.
|
|
48
|
+
|
|
49
|
+
Full documentation: [zharp.io/docs/sdks/python](https://zharp.io/docs/sdks/python)
|
|
50
|
+
|
|
51
|
+
## Install
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
pip install zharp
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Python 3.9+.
|
|
58
|
+
|
|
59
|
+
## Start it
|
|
60
|
+
|
|
61
|
+
Copy your app's key from **Applications → your app → Setup** in Zharp, then call `init()` once,
|
|
62
|
+
before your framework starts:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import zharp
|
|
66
|
+
|
|
67
|
+
zharp.init(key="zpk_…", service="checkout-api", environment="production")
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
- **Django** — at the top of `manage.py` and `wsgi.py` / `asgi.py`.
|
|
71
|
+
- **FastAPI / Flask** — at the top of the module that creates the app, before `FastAPI()` /
|
|
72
|
+
`Flask(__name__)`.
|
|
73
|
+
|
|
74
|
+
That's all. What gets instrumented, when installed: Django, FastAPI, Flask, `requests`, `httpx`,
|
|
75
|
+
`psycopg`, `psycopg2`, SQLAlchemy. Any other OpenTelemetry instrumentation you add is sent too.
|
|
76
|
+
|
|
77
|
+
Leave arguments out to read them from the environment: `ZHARP_KEY`, `ZHARP_SERVICE` (then
|
|
78
|
+
`OTEL_SERVICE_NAME`), `ZHARP_ENVIRONMENT`, `ZHARP_RELEASE`, `ZHARP_ENDPOINT`. `ZHARP_DISABLED=true`
|
|
79
|
+
turns it off.
|
|
80
|
+
|
|
81
|
+
## Users and sessions
|
|
82
|
+
|
|
83
|
+
A browser or mobile app using a Zharp SDK sends `traceparent` and `baggage` (`enduser.id`,
|
|
84
|
+
`session.id`) with its API calls. The request's trace continues from the front end, and every span
|
|
85
|
+
and log of it carries the user and session — nothing to do on the server. When the server knows
|
|
86
|
+
the user better:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
zharp.set_user(id=user.id, email=user.email) # for the rest of this request
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Logs
|
|
93
|
+
|
|
94
|
+
`logging` is bridged: records at `INFO` and above (`logging_level=` to change, `False` to leave
|
|
95
|
+
`logging` alone) are sent with the active trace and the request's user. Or log to Zharp directly:
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
zharp.log.info("Order placed", {"order_id": 42}) # debug, info, warn, error, fatal
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Errors
|
|
102
|
+
|
|
103
|
+
An exception that escapes a request is reported (unhandled) with the request's trace; so is one
|
|
104
|
+
that ends the program or a thread. Report one you caught:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
try:
|
|
108
|
+
charge(order)
|
|
109
|
+
except PaymentError as e:
|
|
110
|
+
zharp.capture_error(e, {"order_id": order.id}) # handled
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`logger.exception(...)` reports too. Each exception is reported once, even when both the
|
|
114
|
+
instrumentation and the framework's logger see it.
|
|
115
|
+
|
|
116
|
+
## Logs only
|
|
117
|
+
|
|
118
|
+
To send logs and errors without tracing:
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
zharp.init(key="zpk_…", service="checkout-api", tracing=False) # or ZHARP_TRACING=false
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Logs (`zharp.log.*` and `logging`), errors (uncaught and `capture_error`), the user, session and
|
|
125
|
+
tags still go out. No spans are recorded or sent, HTTP clients and databases aren't instrumented,
|
|
126
|
+
and no `traceparent`/`baggage` is added to outgoing requests. Django, FastAPI and Flask are hooked
|
|
127
|
+
with a no-op tracer only to read the incoming `traceparent` and `baggage`, so a request's logs still
|
|
128
|
+
carry the caller's trace id, user and session. `zharp.start_span()` runs its work without a span.
|
|
129
|
+
|
|
130
|
+
## More
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
zharp.set_tag("region", "eu-west") # on every span and log after
|
|
134
|
+
with zharp.start_span("render invoice"): # a span around some work
|
|
135
|
+
render(invoice)
|
|
136
|
+
zharp.flush() # send now: end of a job or serverless call
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
| Option | Environment | Default |
|
|
140
|
+
|---|---|---|
|
|
141
|
+
| `key` | `ZHARP_KEY` | — (nothing is sent without one) |
|
|
142
|
+
| `service` | `ZHARP_SERVICE`, `OTEL_SERVICE_NAME` | `name` in `pyproject.toml` |
|
|
143
|
+
| `environment` | `ZHARP_ENVIRONMENT` | none |
|
|
144
|
+
| `release` | `ZHARP_RELEASE` | none |
|
|
145
|
+
| `endpoint` | `ZHARP_ENDPOINT` | `https://api.zharp.io/api/v1/otlp` |
|
|
146
|
+
| `sample_rate` | `ZHARP_SAMPLE_RATE` | `1.0` (share of traces kept; logs and handled errors always sent) |
|
|
147
|
+
| `logging_level` | `ZHARP_LOGGING_LEVEL` | `INFO` |
|
|
148
|
+
| `capture_uncaught` | — | `True` |
|
|
149
|
+
| `instrument` | — | `True` |
|
|
150
|
+
| `tracing` | `ZHARP_TRACING` | `True` (`False`: logs only) |
|
|
151
|
+
|
|
152
|
+
Telemetry is batched and sent every 5 seconds from a background thread, gzip-compressed, and
|
|
153
|
+
whatever is left goes when the program exits. `init()` never raises.
|
|
154
|
+
|
|
155
|
+
## Development
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
python -m venv .venv && .venv/bin/pip install -e . flask fastapi httpx uvicorn
|
|
159
|
+
.venv/bin/python -m unittest discover -s tests
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
`examples/fastapi_app.py` and `examples/crash.py` run against any Zharp endpoint (set `ZHARP_KEY`
|
|
163
|
+
and `ZHARP_ENDPOINT`).
|
|
164
|
+
|
|
165
|
+
### Releasing
|
|
166
|
+
|
|
167
|
+
1. Bump `src/zharp/_version.py`, update `CHANGELOG.md`, run the tests.
|
|
168
|
+
2. `rm -rf dist && python -m build` (or `python -c "from setuptools import build_meta as b; b.build_sdist('dist'); b.build_wheel('dist')"`).
|
|
169
|
+
3. `python -m twine upload dist/*`, then tag `vX.Y.Z`.
|
|
170
|
+
|
|
171
|
+
## License
|
|
172
|
+
|
|
173
|
+
MIT © [Zharp](https://zharp.io)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
zharp/__init__.py,sha256=NEahxdH3F-hPINzunup0R4L67TgG6-LD_VC-hbI2znY,11382
|
|
2
|
+
zharp/_config.py,sha256=wt7pbqDykDKIbs_kVOhEo6FHQweENxftaLFKjS5VTvM,5427
|
|
3
|
+
zharp/_context.py,sha256=VBIPyJMH5IHITGG58ubNnjb-MfnwTnJop4AtDDoiLS4,5986
|
|
4
|
+
zharp/_errors.py,sha256=gMIymOQzOaBg4faqz5O8_8GnwO2ssQK6cmujeVZhLxc,5867
|
|
5
|
+
zharp/_setup.py,sha256=s4Aq_DZGS5SM-KUL1C7AaW2jAi4BhcCKlQstm4RuAjE,14283
|
|
6
|
+
zharp/_version.py,sha256=QTYqXqSTHFRkM9TEgpDFcHvwLbvqHDqvqfQ9EiXkcAM,23
|
|
7
|
+
zharp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
zharp-0.1.0.dist-info/licenses/LICENSE,sha256=p1Zv0Q_gus9IocRVitOerzsNx_65vF6LjbwDQtifnlE,1062
|
|
9
|
+
zharp-0.1.0.dist-info/METADATA,sha256=pLomkeqlzkg3LZCUgI5VgkzI2zHq1ix4ym1-iRov7Jw,6932
|
|
10
|
+
zharp-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
11
|
+
zharp-0.1.0.dist-info/top_level.txt,sha256=xSY_MX8zpMg1x0PJnmKM5Otagfw5NUaeM--quRbA7cM,6
|
|
12
|
+
zharp-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Zharp
|
|
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 @@
|
|
|
1
|
+
zharp
|