visionary-sdk 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. visionary_sdk-0.4.0/.gitignore +7 -0
  2. visionary_sdk-0.4.0/LICENSE +202 -0
  3. visionary_sdk-0.4.0/PKG-INFO +444 -0
  4. visionary_sdk-0.4.0/README.md +409 -0
  5. visionary_sdk-0.4.0/pyproject.toml +51 -0
  6. visionary_sdk-0.4.0/src/visionary/__init__.py +29 -0
  7. visionary_sdk-0.4.0/src/visionary/_agent.py +270 -0
  8. visionary_sdk-0.4.0/src/visionary/_api.py +70 -0
  9. visionary_sdk-0.4.0/src/visionary/_config.py +173 -0
  10. visionary_sdk-0.4.0/src/visionary/_context.py +107 -0
  11. visionary_sdk-0.4.0/src/visionary/_d1.py +84 -0
  12. visionary_sdk-0.4.0/src/visionary/_db.py +256 -0
  13. visionary_sdk-0.4.0/src/visionary/_entry.py +138 -0
  14. visionary_sdk-0.4.0/src/visionary/_errors.py +183 -0
  15. visionary_sdk-0.4.0/src/visionary/_http.py +161 -0
  16. visionary_sdk-0.4.0/src/visionary/_node.py +379 -0
  17. visionary_sdk-0.4.0/src/visionary/_redact.py +106 -0
  18. visionary_sdk-0.4.0/src/visionary/_spans.py +225 -0
  19. visionary_sdk-0.4.0/src/visionary/_storage.py +512 -0
  20. visionary_sdk-0.4.0/src/visionary/_system.py +315 -0
  21. visionary_sdk-0.4.0/src/visionary/_writer.py +339 -0
  22. visionary_sdk-0.4.0/src/visionary/integrations/__init__.py +2 -0
  23. visionary_sdk-0.4.0/src/visionary/integrations/_common.py +81 -0
  24. visionary_sdk-0.4.0/src/visionary/integrations/asgi.py +155 -0
  25. visionary_sdk-0.4.0/src/visionary/integrations/django.py +312 -0
  26. visionary_sdk-0.4.0/src/visionary/integrations/flask.py +235 -0
  27. visionary_sdk-0.4.0/src/visionary/py.typed +0 -0
  28. visionary_sdk-0.4.0/src/visionary/schema/mysql/requests.sql +37 -0
  29. visionary_sdk-0.4.0/src/visionary/schema/mysql/system.sql +76 -0
  30. visionary_sdk-0.4.0/src/visionary/schema/mysql/telemetry.sql +52 -0
  31. visionary_sdk-0.4.0/src/visionary/schema/postgres/requests.sql +37 -0
  32. visionary_sdk-0.4.0/src/visionary/schema/postgres/system.sql +76 -0
  33. visionary_sdk-0.4.0/src/visionary/schema/postgres/telemetry.sql +52 -0
  34. visionary_sdk-0.4.0/src/visionary/schema/sqlite/requests.sql +37 -0
  35. visionary_sdk-0.4.0/src/visionary/schema/sqlite/system.sql +76 -0
  36. visionary_sdk-0.4.0/src/visionary/schema/sqlite/telemetry.sql +52 -0
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ build/
5
+ dist/
6
+ # Copied from the repository root when packing.
7
+ /LICENSE
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,444 @@
1
+ Metadata-Version: 2.5
2
+ Name: visionary-sdk
3
+ Version: 0.4.0
4
+ Summary: Visionary collector: logs API requests, database and HTTP spans, errors and system metrics into your database.
5
+ Project-URL: Homepage, https://github.com/styropyr0/Visionary
6
+ Project-URL: Documentation, https://github.com/styropyr0/Visionary/tree/main/sdks/python#readme
7
+ Project-URL: Source, https://github.com/styropyr0/Visionary/tree/main/sdks/python
8
+ Project-URL: Issues, https://github.com/styropyr0/Visionary/issues
9
+ Author: styropyr0
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: analytics,api,asgi,django,fastapi,flask,metrics,monitoring
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Framework :: Django
15
+ Classifier: Framework :: FastAPI
16
+ Classifier: Framework :: Flask
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Topic :: System :: Monitoring
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.9
24
+ Provides-Extra: all
25
+ Requires-Dist: psutil>=5.9; extra == 'all'
26
+ Requires-Dist: psycopg>=3.1; extra == 'all'
27
+ Requires-Dist: pymysql>=1.0; extra == 'all'
28
+ Provides-Extra: mysql
29
+ Requires-Dist: pymysql>=1.0; extra == 'mysql'
30
+ Provides-Extra: postgres
31
+ Requires-Dist: psycopg>=3.1; extra == 'postgres'
32
+ Provides-Extra: system
33
+ Requires-Dist: psutil>=5.9; extra == 'system'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # visionary-sdk (Python)
37
+
38
+ The Python collector for [Visionary](../../Readme.md). It runs inside your web
39
+ service and writes:
40
+
41
+ - one row per HTTP request into `api_logs` (method, route pattern, status,
42
+ timing, user, redacted headers and bodies, error codes, and how many
43
+ database and outbound HTTP calls it made),
44
+ - the database and HTTP calls of slow or failed requests into `spans`,
45
+ - unhandled and reported exceptions into `errors`,
46
+ - one `releases` row per deploy (when the release is known), and
47
+ - a periodic host / process / runtime sample into `system_metrics`.
48
+
49
+ The Visionary server reads these tables for its dashboards. All slow work
50
+ happens on background threads, so requests are never blocked or slowed. If
51
+ the database is down, the SDK only writes log lines.
52
+
53
+ Every Visionary SDK behaves the same way. The contract is
54
+ [`sdks/SPEC.md`](../SPEC.md).
55
+
56
+ ## Install
57
+
58
+ ```sh
59
+ pip install visionary-sdk # core: stdlib only (D1, SQLite)
60
+ pip install "visionary-sdk[system]" # + psutil: host CPU/memory/network, process CPU/RSS/threads/fds
61
+ pip install "visionary-sdk[postgres]" # + psycopg 3
62
+ pip install "visionary-sdk[mysql]" # + PyMySQL
63
+ ```
64
+
65
+ Requires Python 3.9+. Without the `system` extra, Linux hosts read every host
66
+ and process column from `/proc` instead. On macOS and Windows most of them are
67
+ NULL; disk usage, thread count, GC and HTTP throughput are still recorded.
68
+
69
+ ## Quickstart
70
+
71
+ First configure a database (see [Choosing the database](#choosing-the-database)). For example:
72
+
73
+ ```sh
74
+ export VISIONARY_DATABASE_URL=postgres://user:pass@localhost:5432/app
75
+ ```
76
+
77
+ ### Django
78
+
79
+ ```python
80
+ # settings.py
81
+ MIDDLEWARE = [
82
+ "visionary.integrations.django.VisionaryMiddleware", # first, so it sees the final response
83
+ # ...
84
+ ]
85
+ ```
86
+
87
+ The middleware calls `visionary.init()` the first time it loads, so nothing
88
+ else is needed. It works under WSGI and ASGI, with sync and async views.
89
+
90
+ - **Route:** `request.resolver_match.route` with a leading `/`, e.g. `/users/<int:id>/`.
91
+ - **User:** if you don't call `set_user`, an authenticated `request.user` is
92
+ used (`pk` as the id, `get_username()` as the handle).
93
+
94
+ ### FastAPI / Starlette (any ASGI app)
95
+
96
+ ```python
97
+ from fastapi import FastAPI
98
+ from visionary.integrations.asgi import VisionaryASGIMiddleware
99
+
100
+ app = FastAPI()
101
+ app.add_middleware(VisionaryASGIMiddleware)
102
+ # or, for any ASGI app: app = VisionaryASGIMiddleware(app)
103
+ ```
104
+
105
+ The route is the matched route's path (`/users/{user_id}`). Streaming
106
+ responses keep streaming. Only the first `VISIONARY_LOG_MAX_BODY_BYTES` of a
107
+ body are copied.
108
+
109
+ ### Flask
110
+
111
+ ```python
112
+ from flask import Flask
113
+ from visionary.integrations.flask import Visionary
114
+
115
+ app = Flask(__name__)
116
+ Visionary(app) # or: ext = Visionary(); ext.init_app(app)
117
+ ```
118
+
119
+ The route is `request.url_rule.rule` (`/users/<int:user_id>`).
120
+
121
+ ### Anything else
122
+
123
+ ```python
124
+ import visionary
125
+
126
+ agent = visionary.init() # reads the environment, starts, flushes at exit
127
+ ```
128
+
129
+ `init()` never raises. If no database is configured, it logs one warning and
130
+ returns a no-op agent, and the integrations pass requests straight through.
131
+
132
+ For explicit control (tests, several agents, custom config):
133
+
134
+ ```python
135
+ cfg = visionary.from_env() # or visionary.Config(...)
136
+ cfg.path_prefix = "/api"
137
+ agent = visionary.Agent(cfg).start()
138
+ app.add_middleware(VisionaryASGIMiddleware, agent=agent)
139
+ ...
140
+ agent.close(timeout=10) # drains the queue and flushes samples
141
+ ```
142
+
143
+ ## Choosing the database
144
+
145
+ The SDK checks these in order:
146
+
147
+ 1. **Your own connection.** Use this when the app already has a driver:
148
+
149
+ ```python
150
+ import psycopg, visionary
151
+
152
+ cfg = visionary.from_env()
153
+ cfg.connection_factory = lambda: psycopg.connect(DSN)
154
+ cfg.dialect = "postgres" # "postgres", "mysql" or "sqlite"
155
+ visionary.init(cfg)
156
+ ```
157
+
158
+ The factory must return a new DB-API connection. Visionary keeps that
159
+ connection for its own use:
160
+ - PostgreSQL and MySQL: one shared connection.
161
+ - SQLite: one connection per worker thread.
162
+
163
+ After an error it reconnects through the factory, and it closes the
164
+ connection at shutdown. Each batch runs as one transaction. If you hand it
165
+ an autocommit connection, batches are not atomic.
166
+
167
+ 2. **`VISIONARY_DATABASE_URL`**, chosen by scheme:
168
+
169
+ | URL | Backend |
170
+ |---|---|
171
+ | `postgres://user:pass@host:5432/db` (or `postgresql://`) | PostgreSQL via psycopg 3 |
172
+ | `mysql://user:pass@host:3306/db` | MySQL 8+ / MariaDB via PyMySQL |
173
+ | `sqlite:///absolute/path.db`, `sqlite:///C:/data/x.db`, `sqlite://relative.db` | SQLite via `sqlite3` |
174
+ | `d1://` | Cloudflare D1, credentials from `D1_*` |
175
+
176
+ 3. **Cloudflare D1**, when `D1_ACCOUNT_ID`, `D1_DATABASE_ID` and
177
+ `D1_API_TOKEN` are set. `D1_API_BASE` overrides the API URL.
178
+
179
+ Tables and indexes are created at startup from the schema files shipped in
180
+ the package (`visionary/schema/<dialect>/`). This happens on the background
181
+ threads, so a slow database never delays boot. If the database is down at
182
+ startup, creation is retried before each write.
183
+
184
+ ## Configuration
185
+
186
+ Every setting has an environment variable, and `visionary.Config` has the
187
+ same settings as attributes. The full list and semantics are in
188
+ [SPEC.md, "Environment"](../SPEC.md#environment).
189
+
190
+ | Variable | Default | Notes |
191
+ |---|---|---|
192
+ | `VISIONARY_DATABASE_URL` | | see above |
193
+ | `D1_ACCOUNT_ID`, `D1_DATABASE_ID`, `D1_API_TOKEN`, `D1_API_BASE` | | D1 only |
194
+ | `VISIONARY_INSTANCE` | hostname | labels `system_metrics` rows |
195
+ | `VISIONARY_LOG_REQUESTS` | `true` | request logging on/off |
196
+ | `VISIONARY_LOG_PATH_PREFIX` | empty | only log paths starting with this |
197
+ | `VISIONARY_LOG_BODIES` | `true` | capture request/response bodies |
198
+ | `VISIONARY_LOG_MAX_BODY_BYTES` | `8192` | per body |
199
+ | `VISIONARY_LOG_RETENTION_DAYS` | `30` | `0` keeps forever |
200
+ | `VISIONARY_LOG_REDACT_HEADERS`, `_REDACT_FIELDS`, `_REDACT_REQUEST_FIELDS` | empty | comma lists added to the defaults |
201
+ | `VISIONARY_LOG_ERROR_CODE_FIELD`, `_ERROR_KEY_FIELD` | `error.code`, `error.key` | dotted JSON paths |
202
+ | `VISIONARY_SYSTEM_METRICS` | `true` | sampler on/off |
203
+ | `VISIONARY_SYSTEM_INTERVAL` | `15s` | `15`, `500ms`, `1m` |
204
+ | `VISIONARY_SYSTEM_RETENTION_DAYS` | `30` | |
205
+ | `VISIONARY_SERVICE` | empty | service name on every row |
206
+ | `VISIONARY_RELEASE` | platform commit variable | release on every row; see [Telemetry](#telemetry-spans-errors-releases) |
207
+ | `VISIONARY_SPANS` | `true` | spans and call totals on/off |
208
+ | `VISIONARY_SPAN_THRESHOLD_MS` | `100` | store spans of requests at least this slow (or 5xx) |
209
+ | `VISIONARY_SPAN_MAX` | `100` | span rows per request; later calls still count in the totals |
210
+ | `VISIONARY_ERRORS` | `true` | error capture on/off |
211
+ | `VISIONARY_INSTRUMENT_HTTP` | `false` | Python only: call `instrument_http()` at start |
212
+
213
+ Booleans accept `true/false/1/0/yes/no`.
214
+
215
+ ## Telemetry (spans, errors, releases)
216
+
217
+ ### Service and release
218
+
219
+ `VISIONARY_SERVICE` names the service, so several services can share one
220
+ database. The release (`version`) is `VISIONARY_RELEASE`, else the first of
221
+ `RAILWAY_GIT_COMMIT_SHA`, `RENDER_GIT_COMMIT`, `VERCEL_GIT_COMMIT_SHA`,
222
+ `HEROKU_SLUG_COMMIT`, `SOURCE_VERSION`, `GIT_COMMIT`, `GITHUB_SHA`,
223
+ `K_REVISION`; commit hashes are cut to 12 characters. Both go on every
224
+ `api_logs`, `system_metrics` and `errors` row (`spans`: service only). When
225
+ the release is known, one `releases` row (`sdk = python`, `runtime` such as
226
+ `CPython 3.13.1`) is written at start; the dashboards mark deploys with it.
227
+
228
+ ### Spans
229
+
230
+ Every call the SDK can see is counted into `db_count`, `db_ms`, `http_count`
231
+ and `http_ms` on the request's `api_logs` row (NULL for a kind of call that is
232
+ not instrumented). When the request took at least `VISIONARY_SPAN_THRESHOLD_MS`
233
+ or answered 5xx, its first `VISIONARY_SPAN_MAX` calls are also stored as
234
+ `spans` rows, in start order. Spans outside a request are stored when they
235
+ take at least the threshold themselves, with `request_id` NULL.
236
+
237
+ The request is found through a contextvar, so spans from sync views, thread
238
+ pools that copy the context (FastAPI sync endpoints, `asgiref`,
239
+ `contextvars.copy_context().run`) and asyncio tasks all land on the right
240
+ request.
241
+
242
+ | Source | How |
243
+ |---|---|
244
+ | Django ORM / `connection.cursor()` | automatic: the middleware adds a wrapper to `execute_wrappers` of every database alias |
245
+ | SQLAlchemy (sync or async) | `visionary.instrument_sqlalchemy(engine)` |
246
+ | psycopg 3 (sync/async), psycopg2, PyMySQL, sqlite3 | `conn = visionary.instrument_connection(conn)` (or `instrument_cursor(cur)`) |
247
+ | `requests`, `httpx` (sync and async), `urllib3` | `visionary.instrument_http()` once at startup, or `VISIONARY_INSTRUMENT_HTTP=true` |
248
+ | anything else | `with visionary.span("cache", "GET session"):` (also `async with`) |
249
+
250
+ ```python
251
+ engine = visionary.instrument_sqlalchemy(create_engine(DSN))
252
+
253
+ with visionary.span("queue", "publish order.created", target="rabbitmq") as s:
254
+ channel.basic_publish(...)
255
+ s.set_row_count(1) # optional; s.set_error(...) marks it failed
256
+ ```
257
+
258
+ Database spans are named after the first keyword and main table
259
+ (`SELECT users`, `INSERT bookings`, `BEGIN`), with the target
260
+ `system/database` (`postgresql/app`, `sqlite/app.db`). The statement is stored
261
+ sanitized: string and number literals become `?`, `IN (?, ?, ...)` becomes
262
+ `IN (?)`, whitespace is collapsed. Parameter values are never stored. HTTP
263
+ spans are named `METHOD host`; the detail is the URL without credentials,
264
+ query or fragment. An HTTP span fails on a transport error or a 5xx answer.
265
+ A call through `requests` makes one span, not a second one for urllib3.
266
+
267
+ The SDK's own writes are never recorded as spans.
268
+
269
+ ### Errors
270
+
271
+ The Django, ASGI and Flask integrations record every exception the
272
+ framework turns into a 500 (`handled = 0`) and leave the exception and the
273
+ framework's response unchanged. 4xx exceptions (`Http404`, `HTTPException`,
274
+ `abort(404)`) are not errors. To record one you handled:
275
+
276
+ ```python
277
+ try:
278
+ charge(card)
279
+ except PaymentError:
280
+ visionary.capture_exception() # or capture_exception(exc)
281
+ ```
282
+
283
+ Inside a request the row carries its `request_id`, method, route, path and
284
+ user. `type` is the class name, qualified with its module unless it is a
285
+ builtin (`ValueError`, `psycopg.errors.UndefinedTable`); `stack` is
286
+ `traceback.format_exception` (the last 16 KB).
287
+
288
+ `fingerprint` groups the same error: the first 16 hex characters of
289
+ `sha1(type + "\n" + frames)`, where `frames` are the 5 innermost frames of
290
+ your own code (not the standard library, `site-packages` or this SDK), each
291
+ written `function@path` with the path relative to its `sys.path` entry
292
+ (`shop/views.py`), joined with `\n`. If no frame is your code, the 5
293
+ innermost frames are used; with no frames at all, the message with digit
294
+ runs replaced by `0`. At most 20 rows per fingerprint per minute are kept.
295
+
296
+ Retention: `spans` and `errors` follow `VISIONARY_LOG_RETENTION_DAYS`;
297
+ `releases` are kept.
298
+
299
+ ## Users
300
+
301
+ ```python
302
+ import visionary
303
+
304
+ visionary.set_user(user.id, handle=user.email, role="admin")
305
+ ```
306
+
307
+ Call `set_user` from auth middleware or a view once the user is known. Only
308
+ `id` is required. It is contextvar-based, so it works from sync views, thread
309
+ pools (FastAPI sync endpoints) and asyncio tasks. Outside a request handled
310
+ by an integration, it does nothing.
311
+
312
+ `visionary.set_route("/custom/{pattern}")` works the same way for the route,
313
+ for routers the integration can't see.
314
+
315
+ ## Hooks
316
+
317
+ ```python
318
+ cfg = visionary.from_env()
319
+
320
+ def lookup_user(user_id):
321
+ """Fill in handle/role for ids logged without them. Runs on the writer
322
+ thread, once per distinct user per batch; keep it cheap (cache)."""
323
+ u = USER_CACHE.get(user_id)
324
+ return (u.email, u.role) if u else None
325
+
326
+ def db_stats():
327
+ """Your pool's stats for the db_* columns. Counters are cumulative;
328
+ Visionary stores per-sample deltas."""
329
+ s = pool.get_stats() # e.g. psycopg_pool
330
+ return {
331
+ "total": s["pool_size"], "idle": s["pool_available"],
332
+ "in_use": s["pool_size"] - s["pool_available"], "max": s["pool_max"],
333
+ "acquires": s.get("requests_num", 0), "empty_acquires": s.get("requests_queued", 0),
334
+ "acquire_wait_ms": s.get("requests_wait_ms", 0),
335
+ }
336
+
337
+ cfg.lookup_user = lookup_user
338
+ cfg.db_stats = db_stats
339
+ visionary.init(cfg)
340
+ ```
341
+
342
+ If `db_stats()` leaves out a key, that column is stored as NULL.
343
+
344
+ With Django 5.1+ PostgreSQL pooling (`"OPTIONS": {"pool": ...}`) you don't need
345
+ the hook: when `db_stats` is unset, the Django middleware sums the stats of
346
+ Django's pools the same way. Without a pool the `db_*` columns stay NULL.
347
+
348
+ ## What is captured
349
+
350
+ Each request (`api_logs`) records:
351
+
352
+ - **Request id:** the incoming `X-Request-ID` if it is at most 128 characters,
353
+ otherwise a random 32-hex id. It is echoed on the response.
354
+ - **Timing:** start time (`2026-10-17T17:34:00.123Z`) and duration in ms.
355
+ - **Request line:** method, path, route pattern and query string.
356
+ - **Status:** the final status (500 when the handler raised).
357
+ - **Client:** IP (first `X-Forwarded-For` hop, otherwise the peer address) and user agent.
358
+ - **User:** id, handle and role.
359
+ - **Headers:** all request headers as JSON.
360
+ - **Bodies:** content types, bodies up to the cap with `*_truncated` flags,
361
+ and full body sizes.
362
+ - **Errors:** for `status >= 400`, the error code and key from the JSON response body.
363
+
364
+ Bodies are not captured for `multipart/*`, `image/*`, `video/*`, `audio/*`,
365
+ `application/octet-stream`, `application/zip` and `application/pdf`.
366
+
367
+ Streaming responses are counted, and their first bytes are copied without
368
+ buffering. File responses (`FileResponse`, Flask `send_file`) keep their
369
+ sendfile path, so only their `Content-Length` is recorded.
370
+
371
+ Each sample (`system_metrics`) records:
372
+
373
+ - **Host:** CPU, load average (Unix only), memory, disk usage of the working
374
+ directory, and network rates.
375
+ - **Process:** CPU, RSS, threads and open files.
376
+ - **Runtime:** live Python threads (in the `goroutines` column), the
377
+ `tracemalloc` heap when tracing is on, and GC collections and pause time
378
+ (via `gc.callbacks`).
379
+ - **Database pool:** whatever your `db_stats` hook returns, or Django's
380
+ PostgreSQL pools when it isn't set.
381
+ - **HTTP:** requests, 5xx responses, requests per second and in-flight
382
+ requests seen by the integrations. These are counted even when request
383
+ logging is off.
384
+ - **Node (node-exporter style):**
385
+ - CPU: count, user / system / iowait / steal share.
386
+ - Memory: available and page-cache memory, swap.
387
+ - Disk: total size, inode use, read/write KB/s and IOPS summed over whole
388
+ disks (partitions skipped), average I/O wait (await), and busy % of the
389
+ busiest disk.
390
+ - Network: packets/s, errors and drops.
391
+ - TCP: connections established and retransmits.
392
+ - Processes on the host, running and blocked.
393
+ - Context switches/s.
394
+ - This process: read/write KB/s and its open-file limit.
395
+
396
+ Sources that don't exist on the platform are NULL:
397
+
398
+ - **Linux only:** iowait, steal, disk busy, the TCP columns,
399
+ `procs_running` / `procs_blocked`.
400
+ - **Not on Windows:** page cache, inodes and the open-file limit.
401
+ - **Windows resolution:** disk await comes from whole-second counters there,
402
+ so it is coarse.
403
+
404
+ On Linux the host, process and node columns are read from `/proc` when
405
+ psutil isn't installed, so all of them are filled either way.
406
+
407
+ Older `api_logs` and `system_metrics` tables are upgraded in place at
408
+ startup: missing columns are added with `ALTER TABLE ... ADD COLUMN`, and
409
+ existing rows keep NULL in them.
410
+
411
+ ## Redaction
412
+
413
+ Redaction runs on the writer thread before anything is stored, and all
414
+ matching is case-insensitive.
415
+
416
+ - **Headers:** `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`,
417
+ `X-Api-Key` and `X-Auth-Token` (plus `VISIONARY_LOG_REDACT_HEADERS`) become
418
+ `[REDACTED]`.
419
+ - **JSON keys:** `password`, `passwd`, `secret`, `client_secret`, `token`,
420
+ `access_token`, `refresh_token`, `id_token`, `api_key`, `apikey`, `otp`,
421
+ `pin`, `card_number`, `cvv` and `private_key` (plus
422
+ `VISIONARY_LOG_REDACT_FIELDS`) are redacted in request and response bodies.
423
+ `VISIONARY_LOG_REDACT_REQUEST_FIELDS` adds keys redacted in request bodies
424
+ only.
425
+ - **Truncated bodies:** matching uses a regex, so bodies cut at the cap are
426
+ still scrubbed.
427
+ - **Form bodies:** `application/x-www-form-urlencoded` request bodies are
428
+ scrubbed the same way (`password=[REDACTED]`).
429
+
430
+ ## Operational notes
431
+
432
+ - **Request queue:** holds 5000 entries. When it is full, new entries are
433
+ dropped and the count is logged.
434
+ - **Request writes:** batches of up to 50 are written every 3 s. A failed
435
+ batch is retried up to 3 times (1 s, then 2 s backoff), then dropped with an
436
+ error log.
437
+ - **System writes:** samples are written 4 at a time. On failure they are kept
438
+ (at most an hour's worth) and retried with the next write.
439
+ - **Retention:** runs 60 s after start, then daily, deleting in chunks of 5000.
440
+ - **Telemetry writes:** spans, errors and the release row share the request
441
+ queue and batches (one transaction, or one D1 `batch` call, per flush).
442
+ - **Logging:** all messages go to the `visionary` logger.
443
+ - **Forking servers:** with servers like `gunicorn --preload`, the background
444
+ threads are restarted in each worker after fork.