zharp 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- zharp-0.1.0/LICENSE +21 -0
- zharp-0.1.0/PKG-INFO +173 -0
- zharp-0.1.0/README.md +133 -0
- zharp-0.1.0/pyproject.toml +58 -0
- zharp-0.1.0/setup.cfg +4 -0
- zharp-0.1.0/src/zharp/__init__.py +298 -0
- zharp-0.1.0/src/zharp/_config.py +161 -0
- zharp-0.1.0/src/zharp/_context.py +154 -0
- zharp-0.1.0/src/zharp/_errors.py +156 -0
- zharp-0.1.0/src/zharp/_setup.py +340 -0
- zharp-0.1.0/src/zharp/_version.py +1 -0
- zharp-0.1.0/src/zharp/py.typed +0 -0
- zharp-0.1.0/src/zharp.egg-info/PKG-INFO +173 -0
- zharp-0.1.0/src/zharp.egg-info/SOURCES.txt +17 -0
- zharp-0.1.0/src/zharp.egg-info/dependency_links.txt +1 -0
- zharp-0.1.0/src/zharp.egg-info/requires.txt +13 -0
- zharp-0.1.0/src/zharp.egg-info/top_level.txt +1 -0
- zharp-0.1.0/tests/test_logs_only.py +63 -0
- zharp-0.1.0/tests/test_zharp.py +263 -0
zharp-0.1.0/LICENSE
ADDED
|
@@ -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.
|
zharp-0.1.0/PKG-INFO
ADDED
|
@@ -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)
|
zharp-0.1.0/README.md
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# zharp
|
|
2
|
+
|
|
3
|
+
[Zharp](https://zharp.io) Application Monitoring for Python: every request traced, outgoing HTTP
|
|
4
|
+
calls and database queries timed, `logging` records sent with their trace, and errors grouped into
|
|
5
|
+
issues. Built on the official [OpenTelemetry](https://opentelemetry.io) SDK — `zharp` only
|
|
6
|
+
configures it (exporter, resource, propagation, the `logging` bridge) and turns on the
|
|
7
|
+
instrumentations for the libraries you have.
|
|
8
|
+
|
|
9
|
+
Full documentation: [zharp.io/docs/sdks/python](https://zharp.io/docs/sdks/python)
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install zharp
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Python 3.9+.
|
|
18
|
+
|
|
19
|
+
## Start it
|
|
20
|
+
|
|
21
|
+
Copy your app's key from **Applications → your app → Setup** in Zharp, then call `init()` once,
|
|
22
|
+
before your framework starts:
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
import zharp
|
|
26
|
+
|
|
27
|
+
zharp.init(key="zpk_…", service="checkout-api", environment="production")
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
- **Django** — at the top of `manage.py` and `wsgi.py` / `asgi.py`.
|
|
31
|
+
- **FastAPI / Flask** — at the top of the module that creates the app, before `FastAPI()` /
|
|
32
|
+
`Flask(__name__)`.
|
|
33
|
+
|
|
34
|
+
That's all. What gets instrumented, when installed: Django, FastAPI, Flask, `requests`, `httpx`,
|
|
35
|
+
`psycopg`, `psycopg2`, SQLAlchemy. Any other OpenTelemetry instrumentation you add is sent too.
|
|
36
|
+
|
|
37
|
+
Leave arguments out to read them from the environment: `ZHARP_KEY`, `ZHARP_SERVICE` (then
|
|
38
|
+
`OTEL_SERVICE_NAME`), `ZHARP_ENVIRONMENT`, `ZHARP_RELEASE`, `ZHARP_ENDPOINT`. `ZHARP_DISABLED=true`
|
|
39
|
+
turns it off.
|
|
40
|
+
|
|
41
|
+
## Users and sessions
|
|
42
|
+
|
|
43
|
+
A browser or mobile app using a Zharp SDK sends `traceparent` and `baggage` (`enduser.id`,
|
|
44
|
+
`session.id`) with its API calls. The request's trace continues from the front end, and every span
|
|
45
|
+
and log of it carries the user and session — nothing to do on the server. When the server knows
|
|
46
|
+
the user better:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
zharp.set_user(id=user.id, email=user.email) # for the rest of this request
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Logs
|
|
53
|
+
|
|
54
|
+
`logging` is bridged: records at `INFO` and above (`logging_level=` to change, `False` to leave
|
|
55
|
+
`logging` alone) are sent with the active trace and the request's user. Or log to Zharp directly:
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
zharp.log.info("Order placed", {"order_id": 42}) # debug, info, warn, error, fatal
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Errors
|
|
62
|
+
|
|
63
|
+
An exception that escapes a request is reported (unhandled) with the request's trace; so is one
|
|
64
|
+
that ends the program or a thread. Report one you caught:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
try:
|
|
68
|
+
charge(order)
|
|
69
|
+
except PaymentError as e:
|
|
70
|
+
zharp.capture_error(e, {"order_id": order.id}) # handled
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
`logger.exception(...)` reports too. Each exception is reported once, even when both the
|
|
74
|
+
instrumentation and the framework's logger see it.
|
|
75
|
+
|
|
76
|
+
## Logs only
|
|
77
|
+
|
|
78
|
+
To send logs and errors without tracing:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
zharp.init(key="zpk_…", service="checkout-api", tracing=False) # or ZHARP_TRACING=false
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Logs (`zharp.log.*` and `logging`), errors (uncaught and `capture_error`), the user, session and
|
|
85
|
+
tags still go out. No spans are recorded or sent, HTTP clients and databases aren't instrumented,
|
|
86
|
+
and no `traceparent`/`baggage` is added to outgoing requests. Django, FastAPI and Flask are hooked
|
|
87
|
+
with a no-op tracer only to read the incoming `traceparent` and `baggage`, so a request's logs still
|
|
88
|
+
carry the caller's trace id, user and session. `zharp.start_span()` runs its work without a span.
|
|
89
|
+
|
|
90
|
+
## More
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
zharp.set_tag("region", "eu-west") # on every span and log after
|
|
94
|
+
with zharp.start_span("render invoice"): # a span around some work
|
|
95
|
+
render(invoice)
|
|
96
|
+
zharp.flush() # send now: end of a job or serverless call
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
| Option | Environment | Default |
|
|
100
|
+
|---|---|---|
|
|
101
|
+
| `key` | `ZHARP_KEY` | — (nothing is sent without one) |
|
|
102
|
+
| `service` | `ZHARP_SERVICE`, `OTEL_SERVICE_NAME` | `name` in `pyproject.toml` |
|
|
103
|
+
| `environment` | `ZHARP_ENVIRONMENT` | none |
|
|
104
|
+
| `release` | `ZHARP_RELEASE` | none |
|
|
105
|
+
| `endpoint` | `ZHARP_ENDPOINT` | `https://api.zharp.io/api/v1/otlp` |
|
|
106
|
+
| `sample_rate` | `ZHARP_SAMPLE_RATE` | `1.0` (share of traces kept; logs and handled errors always sent) |
|
|
107
|
+
| `logging_level` | `ZHARP_LOGGING_LEVEL` | `INFO` |
|
|
108
|
+
| `capture_uncaught` | — | `True` |
|
|
109
|
+
| `instrument` | — | `True` |
|
|
110
|
+
| `tracing` | `ZHARP_TRACING` | `True` (`False`: logs only) |
|
|
111
|
+
|
|
112
|
+
Telemetry is batched and sent every 5 seconds from a background thread, gzip-compressed, and
|
|
113
|
+
whatever is left goes when the program exits. `init()` never raises.
|
|
114
|
+
|
|
115
|
+
## Development
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
python -m venv .venv && .venv/bin/pip install -e . flask fastapi httpx uvicorn
|
|
119
|
+
.venv/bin/python -m unittest discover -s tests
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`examples/fastapi_app.py` and `examples/crash.py` run against any Zharp endpoint (set `ZHARP_KEY`
|
|
123
|
+
and `ZHARP_ENDPOINT`).
|
|
124
|
+
|
|
125
|
+
### Releasing
|
|
126
|
+
|
|
127
|
+
1. Bump `src/zharp/_version.py`, update `CHANGELOG.md`, run the tests.
|
|
128
|
+
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')"`).
|
|
129
|
+
3. `python -m twine upload dist/*`, then tag `vX.Y.Z`.
|
|
130
|
+
|
|
131
|
+
## License
|
|
132
|
+
|
|
133
|
+
MIT © [Zharp](https://zharp.io)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "zharp"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Zharp Application Monitoring for Python: traces, logs and errors from Django, FastAPI and Flask, on OpenTelemetry."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
authors = [{ name = "Zharp", email = "support@zharp.io" }]
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
keywords = ["apm", "tracing", "opentelemetry", "logging", "errors", "observability", "monitoring", "zharp"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Framework :: Django",
|
|
20
|
+
"Framework :: FastAPI",
|
|
21
|
+
"Framework :: Flask",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
24
|
+
"Topic :: System :: Logging",
|
|
25
|
+
"Topic :: System :: Monitoring",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
]
|
|
28
|
+
# The instrumentation packages don't install the frameworks they instrument; init() instruments
|
|
29
|
+
# the ones the app has.
|
|
30
|
+
dependencies = [
|
|
31
|
+
"opentelemetry-api>=1.40,<2",
|
|
32
|
+
"opentelemetry-sdk>=1.40,<2",
|
|
33
|
+
"opentelemetry-exporter-otlp-proto-http>=1.40,<2",
|
|
34
|
+
"opentelemetry-instrumentation>=0.61b0",
|
|
35
|
+
"opentelemetry-instrumentation-logging>=0.61b0",
|
|
36
|
+
"opentelemetry-instrumentation-django>=0.61b0",
|
|
37
|
+
"opentelemetry-instrumentation-fastapi>=0.61b0",
|
|
38
|
+
"opentelemetry-instrumentation-flask>=0.61b0",
|
|
39
|
+
"opentelemetry-instrumentation-requests>=0.61b0",
|
|
40
|
+
"opentelemetry-instrumentation-httpx>=0.61b0",
|
|
41
|
+
"opentelemetry-instrumentation-psycopg>=0.61b0",
|
|
42
|
+
"opentelemetry-instrumentation-psycopg2>=0.61b0",
|
|
43
|
+
"opentelemetry-instrumentation-sqlalchemy>=0.61b0",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
[project.urls]
|
|
47
|
+
Homepage = "https://zharp.io"
|
|
48
|
+
Documentation = "https://zharp.io/docs/sdks/python"
|
|
49
|
+
Source = "https://github.com/zharp-io/zharp-python-lib"
|
|
50
|
+
|
|
51
|
+
[tool.setuptools.dynamic]
|
|
52
|
+
version = { attr = "zharp._version.__version__" }
|
|
53
|
+
|
|
54
|
+
[tool.setuptools.packages.find]
|
|
55
|
+
where = ["src"]
|
|
56
|
+
|
|
57
|
+
[tool.setuptools.package-data]
|
|
58
|
+
zharp = ["py.typed"]
|
zharp-0.1.0/setup.cfg
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)
|