loggerai-sdk 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.
- loggerai_sdk-0.1.0/.github/workflows/release.yml +37 -0
- loggerai_sdk-0.1.0/.gitignore +7 -0
- loggerai_sdk-0.1.0/LICENSE +21 -0
- loggerai_sdk-0.1.0/PKG-INFO +166 -0
- loggerai_sdk-0.1.0/README.md +145 -0
- loggerai_sdk-0.1.0/pyproject.toml +38 -0
- loggerai_sdk-0.1.0/src/loggerai/__init__.py +122 -0
- loggerai_sdk-0.1.0/src/loggerai/_version.py +1 -0
- loggerai_sdk-0.1.0/src/loggerai/asgi.py +60 -0
- loggerai_sdk-0.1.0/src/loggerai/celery.py +44 -0
- loggerai_sdk-0.1.0/src/loggerai/client.py +284 -0
- loggerai_sdk-0.1.0/src/loggerai/context.py +79 -0
- loggerai_sdk-0.1.0/src/loggerai/django.py +102 -0
- loggerai_sdk-0.1.0/src/loggerai/flask.py +42 -0
- loggerai_sdk-0.1.0/src/loggerai/frames.py +41 -0
- loggerai_sdk-0.1.0/src/loggerai/instrument.py +215 -0
- loggerai_sdk-0.1.0/src/loggerai/redact.py +99 -0
- loggerai_sdk-0.1.0/src/loggerai/wsgi.py +39 -0
- loggerai_sdk-0.1.0/tests/conftest.py +56 -0
- loggerai_sdk-0.1.0/tests/test_sdk.py +205 -0
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
name: Test and publish
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
tags: ["v*"]
|
|
7
|
+
pull_request:
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
test:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
strategy:
|
|
13
|
+
matrix:
|
|
14
|
+
python: ["3.8", "3.10", "3.12", "3.13"]
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v4
|
|
17
|
+
- uses: actions/setup-python@v5
|
|
18
|
+
with:
|
|
19
|
+
python-version: ${{ matrix.python }}
|
|
20
|
+
- run: pip install -e . pytest fastapi httpx flask django sqlalchemy requests
|
|
21
|
+
- run: pytest -q
|
|
22
|
+
|
|
23
|
+
publish:
|
|
24
|
+
# A tag like v0.1.0 publishes that version to PyPI (trusted publishing: no token stored).
|
|
25
|
+
if: startsWith(github.ref, 'refs/tags/v')
|
|
26
|
+
needs: test
|
|
27
|
+
runs-on: ubuntu-latest
|
|
28
|
+
environment: pypi
|
|
29
|
+
permissions:
|
|
30
|
+
id-token: write
|
|
31
|
+
steps:
|
|
32
|
+
- uses: actions/checkout@v4
|
|
33
|
+
- uses: actions/setup-python@v5
|
|
34
|
+
with:
|
|
35
|
+
python-version: "3.12"
|
|
36
|
+
- run: pip install build && python -m build
|
|
37
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 LoggerAI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: loggerai-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LoggerAI for Python: performance monitoring, errors, logs and health checks for FastAPI, Django, Flask and Celery.
|
|
5
|
+
Project-URL: Homepage, https://loggerai.uk
|
|
6
|
+
Project-URL: Source, https://github.com/ehisakhile/loggerai-python
|
|
7
|
+
Author-email: LoggerAI <dev@loggerai.uk>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: apm,django,errors,fastapi,flask,logging,monitoring,observability
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Framework :: Django
|
|
13
|
+
Classifier: Framework :: FastAPI
|
|
14
|
+
Classifier: Framework :: Flask
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Topic :: System :: Monitoring
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# LoggerAI for Python
|
|
23
|
+
|
|
24
|
+
Performance monitoring, errors, logs and health checks for FastAPI,
|
|
25
|
+
Starlette, Django, Flask and Celery, with AI that explains what went wrong.
|
|
26
|
+
|
|
27
|
+
- **Every endpoint** timed under its route template (`/orders/{order_id}`):
|
|
28
|
+
p50/p95/p99, Apdex, status codes, slow and failed requests.
|
|
29
|
+
- **What each request waits on**: database queries (SQLAlchemy and Django),
|
|
30
|
+
outgoing HTTP (`httpx`, `requests`), Redis.
|
|
31
|
+
- **Exceptions**, grouped by cause, with stack traces that show your code first.
|
|
32
|
+
- **Logs** at warning and above.
|
|
33
|
+
- **Health checks** you define (database, cache, a queue).
|
|
34
|
+
- **Background work** (Celery tasks, scripts) timed like requests.
|
|
35
|
+
- **Browser sessions** recorded by LoggerAI's browser script link to the
|
|
36
|
+
server request each click caused (`traceparent`, `x-loggerai-session`).
|
|
37
|
+
|
|
38
|
+
The package is `loggerai-sdk`; you import it as `loggerai`.
|
|
39
|
+
|
|
40
|
+
Secrets (passwords, tokens, cookies, API keys, JWTs) are masked before
|
|
41
|
+
anything leaves your server, request and response bodies are never sent, and
|
|
42
|
+
users are counted by a one-way hash of their id. No dependencies; Python 3.8+.
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install loggerai-sdk
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Get your project's **secret key** (`sk_live_...`) from LoggerAI → your
|
|
51
|
+
project → **Connect**, and set it in the environment:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
LOGGERAI_KEY=sk_live_...
|
|
55
|
+
LOGGERAI_RELEASE=$GIT_SHA # optional: "since release X"
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Without a key nothing is recorded or sent, so local development stays quiet.
|
|
59
|
+
|
|
60
|
+
### FastAPI / Starlette
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
import loggerai
|
|
64
|
+
from loggerai.asgi import LoggerAIMiddleware
|
|
65
|
+
|
|
66
|
+
loggerai.init()
|
|
67
|
+
app = FastAPI()
|
|
68
|
+
app.add_middleware(LoggerAIMiddleware)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Django
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
# settings.py
|
|
75
|
+
import loggerai
|
|
76
|
+
loggerai.init()
|
|
77
|
+
|
|
78
|
+
MIDDLEWARE = [
|
|
79
|
+
"loggerai.django.LoggerAIMiddleware", # first
|
|
80
|
+
...
|
|
81
|
+
]
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### Flask
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
import loggerai, loggerai.flask
|
|
88
|
+
|
|
89
|
+
loggerai.init()
|
|
90
|
+
app = Flask(__name__)
|
|
91
|
+
loggerai.flask.instrument(app)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Celery
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
import loggerai, loggerai.celery
|
|
98
|
+
|
|
99
|
+
loggerai.init(service="worker")
|
|
100
|
+
loggerai.celery.instrument()
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Any other WSGI app
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
from loggerai.wsgi import LoggerAIMiddleware
|
|
107
|
+
application = LoggerAIMiddleware(application)
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Health checks
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
def database():
|
|
114
|
+
with engine.connect() as c:
|
|
115
|
+
c.execute(text("SELECT 1"))
|
|
116
|
+
return True # or (False, "why")
|
|
117
|
+
|
|
118
|
+
loggerai.init(health_checks={"database": database, "redis": lambda: r.ping()})
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
They run every minute in the background and show on the project's health
|
|
122
|
+
page; alert on them from the dashboard.
|
|
123
|
+
|
|
124
|
+
## More
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
loggerai.set_user(request.user.id) # only a one-way hash is sent
|
|
128
|
+
|
|
129
|
+
with loggerai.measure("api.stripe.com", "POST"): # calls it can't see itself
|
|
130
|
+
stripe.PaymentIntent.confirm(intent_id)
|
|
131
|
+
|
|
132
|
+
with loggerai.track("job", "send_invoices"): # scripts, cron jobs
|
|
133
|
+
send_invoices()
|
|
134
|
+
|
|
135
|
+
try:
|
|
136
|
+
risky()
|
|
137
|
+
except ValueError as e:
|
|
138
|
+
loggerai.capture_exception(e, order=order.id) # handled, but worth seeing
|
|
139
|
+
|
|
140
|
+
loggerai.flush() # at the end of a short script or a serverless call
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Settings
|
|
144
|
+
|
|
145
|
+
| Environment | `init()` | Default | |
|
|
146
|
+
|---|---|---|---|
|
|
147
|
+
| `LOGGERAI_KEY` | `key` | — | Secret key; off without it |
|
|
148
|
+
| `LOGGERAI_SERVICE` | `service` | `app` | Name this process (`api`, `worker`) |
|
|
149
|
+
| `LOGGERAI_ENVIRONMENT` | `environment` | `production` | Separates production from staging |
|
|
150
|
+
| `LOGGERAI_RELEASE` | `release` | — | Version or git SHA |
|
|
151
|
+
| `LOGGERAI_ENABLED` | `enabled` | `true` | Turn it off without removing the key |
|
|
152
|
+
| | `logs_level` | `"WARNING"` | Lowest log level sent; `None` for no logs |
|
|
153
|
+
| | `ignore_paths` | `/health`, `/up`, … | Paths not recorded |
|
|
154
|
+
| | `capture_queries`, `capture_http`, `capture_redis` | `True` | |
|
|
155
|
+
| | `flush_interval` | `5` | Seconds between batches |
|
|
156
|
+
|
|
157
|
+
## How it sends
|
|
158
|
+
|
|
159
|
+
Records are kept in memory and sent from a background thread every few
|
|
160
|
+
seconds, gzipped, with a 2-second timeout. Requests never wait on LoggerAI.
|
|
161
|
+
If it can't be reached, records are dropped instead of piling up. With
|
|
162
|
+
gunicorn or uWSGI, each worker process sends its own batches.
|
|
163
|
+
|
|
164
|
+
## Support
|
|
165
|
+
|
|
166
|
+
dev@loggerai.uk · https://loggerai.uk
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
# LoggerAI for Python
|
|
2
|
+
|
|
3
|
+
Performance monitoring, errors, logs and health checks for FastAPI,
|
|
4
|
+
Starlette, Django, Flask and Celery, with AI that explains what went wrong.
|
|
5
|
+
|
|
6
|
+
- **Every endpoint** timed under its route template (`/orders/{order_id}`):
|
|
7
|
+
p50/p95/p99, Apdex, status codes, slow and failed requests.
|
|
8
|
+
- **What each request waits on**: database queries (SQLAlchemy and Django),
|
|
9
|
+
outgoing HTTP (`httpx`, `requests`), Redis.
|
|
10
|
+
- **Exceptions**, grouped by cause, with stack traces that show your code first.
|
|
11
|
+
- **Logs** at warning and above.
|
|
12
|
+
- **Health checks** you define (database, cache, a queue).
|
|
13
|
+
- **Background work** (Celery tasks, scripts) timed like requests.
|
|
14
|
+
- **Browser sessions** recorded by LoggerAI's browser script link to the
|
|
15
|
+
server request each click caused (`traceparent`, `x-loggerai-session`).
|
|
16
|
+
|
|
17
|
+
The package is `loggerai-sdk`; you import it as `loggerai`.
|
|
18
|
+
|
|
19
|
+
Secrets (passwords, tokens, cookies, API keys, JWTs) are masked before
|
|
20
|
+
anything leaves your server, request and response bodies are never sent, and
|
|
21
|
+
users are counted by a one-way hash of their id. No dependencies; Python 3.8+.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install loggerai-sdk
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Get your project's **secret key** (`sk_live_...`) from LoggerAI → your
|
|
30
|
+
project → **Connect**, and set it in the environment:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
LOGGERAI_KEY=sk_live_...
|
|
34
|
+
LOGGERAI_RELEASE=$GIT_SHA # optional: "since release X"
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Without a key nothing is recorded or sent, so local development stays quiet.
|
|
38
|
+
|
|
39
|
+
### FastAPI / Starlette
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
import loggerai
|
|
43
|
+
from loggerai.asgi import LoggerAIMiddleware
|
|
44
|
+
|
|
45
|
+
loggerai.init()
|
|
46
|
+
app = FastAPI()
|
|
47
|
+
app.add_middleware(LoggerAIMiddleware)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Django
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
# settings.py
|
|
54
|
+
import loggerai
|
|
55
|
+
loggerai.init()
|
|
56
|
+
|
|
57
|
+
MIDDLEWARE = [
|
|
58
|
+
"loggerai.django.LoggerAIMiddleware", # first
|
|
59
|
+
...
|
|
60
|
+
]
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Flask
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
import loggerai, loggerai.flask
|
|
67
|
+
|
|
68
|
+
loggerai.init()
|
|
69
|
+
app = Flask(__name__)
|
|
70
|
+
loggerai.flask.instrument(app)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Celery
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
import loggerai, loggerai.celery
|
|
77
|
+
|
|
78
|
+
loggerai.init(service="worker")
|
|
79
|
+
loggerai.celery.instrument()
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### Any other WSGI app
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from loggerai.wsgi import LoggerAIMiddleware
|
|
86
|
+
application = LoggerAIMiddleware(application)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Health checks
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
def database():
|
|
93
|
+
with engine.connect() as c:
|
|
94
|
+
c.execute(text("SELECT 1"))
|
|
95
|
+
return True # or (False, "why")
|
|
96
|
+
|
|
97
|
+
loggerai.init(health_checks={"database": database, "redis": lambda: r.ping()})
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
They run every minute in the background and show on the project's health
|
|
101
|
+
page; alert on them from the dashboard.
|
|
102
|
+
|
|
103
|
+
## More
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
loggerai.set_user(request.user.id) # only a one-way hash is sent
|
|
107
|
+
|
|
108
|
+
with loggerai.measure("api.stripe.com", "POST"): # calls it can't see itself
|
|
109
|
+
stripe.PaymentIntent.confirm(intent_id)
|
|
110
|
+
|
|
111
|
+
with loggerai.track("job", "send_invoices"): # scripts, cron jobs
|
|
112
|
+
send_invoices()
|
|
113
|
+
|
|
114
|
+
try:
|
|
115
|
+
risky()
|
|
116
|
+
except ValueError as e:
|
|
117
|
+
loggerai.capture_exception(e, order=order.id) # handled, but worth seeing
|
|
118
|
+
|
|
119
|
+
loggerai.flush() # at the end of a short script or a serverless call
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Settings
|
|
123
|
+
|
|
124
|
+
| Environment | `init()` | Default | |
|
|
125
|
+
|---|---|---|---|
|
|
126
|
+
| `LOGGERAI_KEY` | `key` | — | Secret key; off without it |
|
|
127
|
+
| `LOGGERAI_SERVICE` | `service` | `app` | Name this process (`api`, `worker`) |
|
|
128
|
+
| `LOGGERAI_ENVIRONMENT` | `environment` | `production` | Separates production from staging |
|
|
129
|
+
| `LOGGERAI_RELEASE` | `release` | — | Version or git SHA |
|
|
130
|
+
| `LOGGERAI_ENABLED` | `enabled` | `true` | Turn it off without removing the key |
|
|
131
|
+
| | `logs_level` | `"WARNING"` | Lowest log level sent; `None` for no logs |
|
|
132
|
+
| | `ignore_paths` | `/health`, `/up`, … | Paths not recorded |
|
|
133
|
+
| | `capture_queries`, `capture_http`, `capture_redis` | `True` | |
|
|
134
|
+
| | `flush_interval` | `5` | Seconds between batches |
|
|
135
|
+
|
|
136
|
+
## How it sends
|
|
137
|
+
|
|
138
|
+
Records are kept in memory and sent from a background thread every few
|
|
139
|
+
seconds, gzipped, with a 2-second timeout. Requests never wait on LoggerAI.
|
|
140
|
+
If it can't be reached, records are dropped instead of piling up. With
|
|
141
|
+
gunicorn or uWSGI, each worker process sends its own batches.
|
|
142
|
+
|
|
143
|
+
## Support
|
|
144
|
+
|
|
145
|
+
dev@loggerai.uk · https://loggerai.uk
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.18"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "loggerai-sdk"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "LoggerAI for Python: performance monitoring, errors, logs and health checks for FastAPI, Django, Flask and Celery."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.8"
|
|
13
|
+
authors = [{ name = "LoggerAI", email = "dev@loggerai.uk" }]
|
|
14
|
+
keywords = ["monitoring", "apm", "observability", "fastapi", "django", "flask", "errors", "logging"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Framework :: Django",
|
|
18
|
+
"Framework :: FastAPI",
|
|
19
|
+
"Framework :: Flask",
|
|
20
|
+
"Intended Audience :: Developers",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Topic :: System :: Monitoring",
|
|
24
|
+
]
|
|
25
|
+
dependencies = []
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://loggerai.uk"
|
|
29
|
+
Source = "https://github.com/ehisakhile/loggerai-python"
|
|
30
|
+
|
|
31
|
+
[tool.hatch.version]
|
|
32
|
+
path = "src/loggerai/_version.py"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/loggerai"]
|
|
36
|
+
|
|
37
|
+
[tool.pytest.ini_options]
|
|
38
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""
|
|
2
|
+
LoggerAI for Python: performance monitoring, errors, logs and health checks
|
|
3
|
+
for FastAPI, Starlette, Django, Flask and Celery.
|
|
4
|
+
|
|
5
|
+
import loggerai
|
|
6
|
+
loggerai.init() # reads LOGGERAI_KEY (sk_live_...)
|
|
7
|
+
|
|
8
|
+
# FastAPI / Starlette
|
|
9
|
+
from loggerai.asgi import LoggerAIMiddleware
|
|
10
|
+
app.add_middleware(LoggerAIMiddleware)
|
|
11
|
+
|
|
12
|
+
Nothing is sent without a key, nothing ever raises into your app, and
|
|
13
|
+
secrets are masked before anything leaves it.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import contextlib
|
|
18
|
+
import time
|
|
19
|
+
from typing import Any, Callable, Dict, Iterator, Optional
|
|
20
|
+
|
|
21
|
+
from . import context
|
|
22
|
+
from ._version import __version__
|
|
23
|
+
from .client import Client, get_client, set_client
|
|
24
|
+
|
|
25
|
+
__all__ = ["init", "capture_exception", "set_user", "set_route", "measure", "track", "flush", "health_checks", "Client", "__version__"]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def init(key: Optional[str] = None, **options: Any) -> Client:
|
|
29
|
+
"""Start LoggerAI. Every option also has an environment variable:
|
|
30
|
+
key (LOGGERAI_KEY), endpoint, service, environment, release, enabled.
|
|
31
|
+
Others: logs_level ("WARNING", or None for no logs), capture_queries,
|
|
32
|
+
capture_http, capture_redis, ignore_paths, health_checks={"database": fn},
|
|
33
|
+
flush_interval (seconds), timeout, root (the app's folder, for stack traces)."""
|
|
34
|
+
old = get_client()
|
|
35
|
+
if old is not None:
|
|
36
|
+
old.close(timeout=1.0)
|
|
37
|
+
client = Client(key, **options)
|
|
38
|
+
set_client(client)
|
|
39
|
+
if client.enabled:
|
|
40
|
+
from . import instrument
|
|
41
|
+
instrument.all_from(client)
|
|
42
|
+
if client.health_checks:
|
|
43
|
+
client.start()
|
|
44
|
+
return client
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def capture_exception(exc: Optional[BaseException] = None, **extra: Any) -> None:
|
|
48
|
+
"""Report an exception you handled but still want to see."""
|
|
49
|
+
import sys
|
|
50
|
+
exc = exc or sys.exc_info()[1]
|
|
51
|
+
client = get_client()
|
|
52
|
+
if exc is not None and client is not None:
|
|
53
|
+
client.exception(exc, handled=True, extra=extra or None)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def set_user(user_id: Any) -> None:
|
|
57
|
+
"""Count the current request against a user. Only a one-way hash of the id is sent."""
|
|
58
|
+
unit, client = context.current.get(), get_client()
|
|
59
|
+
if unit is not None and client is not None:
|
|
60
|
+
unit.user = client.user_ref(user_id)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def set_route(template: str) -> None:
|
|
64
|
+
"""Name the current request yourself (a template like /orders/{id}, never a raw path)."""
|
|
65
|
+
unit = context.current.get()
|
|
66
|
+
if unit is not None:
|
|
67
|
+
unit.route = template
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@contextlib.contextmanager
|
|
71
|
+
def measure(target: str, operation: str = "CALL") -> Iterator[None]:
|
|
72
|
+
"""Time a call LoggerAI can't see on its own, e.g. an SDK with its own HTTP client:
|
|
73
|
+
|
|
74
|
+
with loggerai.measure("api.stripe.com", "POST"):
|
|
75
|
+
stripe.PaymentIntent.confirm(...)
|
|
76
|
+
"""
|
|
77
|
+
t = time.perf_counter()
|
|
78
|
+
ok = False
|
|
79
|
+
try:
|
|
80
|
+
yield
|
|
81
|
+
ok = True
|
|
82
|
+
finally:
|
|
83
|
+
context.dependency(target, operation, (time.perf_counter() - t) * 1000, ok)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@contextlib.contextmanager
|
|
87
|
+
def track(kind: str, name: str) -> Iterator[context.Unit]:
|
|
88
|
+
"""Time a unit of work outside a web request: a job, a scheduled task, a script.
|
|
89
|
+
|
|
90
|
+
with loggerai.track("job", "send_invoices"):
|
|
91
|
+
...
|
|
92
|
+
"""
|
|
93
|
+
client = get_client()
|
|
94
|
+
unit = context.Unit(kind if kind in ("job", "command", "http") else "job", "JOB" if kind != "command" else "CLI")
|
|
95
|
+
unit.route = name
|
|
96
|
+
token = context.current.set(unit)
|
|
97
|
+
status = 200
|
|
98
|
+
try:
|
|
99
|
+
yield unit
|
|
100
|
+
except Exception as e:
|
|
101
|
+
status = 500
|
|
102
|
+
if client is not None:
|
|
103
|
+
client.exception(e, status=500)
|
|
104
|
+
raise
|
|
105
|
+
finally:
|
|
106
|
+
context.current.reset(token)
|
|
107
|
+
if client is not None:
|
|
108
|
+
client.finish(unit, status)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def flush(timeout: float = 5.0) -> bool:
|
|
112
|
+
"""Send everything now (e.g. at the end of a script or a serverless call)."""
|
|
113
|
+
client = get_client()
|
|
114
|
+
return client.flush(timeout) if client is not None else True
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def health_checks(checks: Dict[str, Callable[[], Any]]) -> None:
|
|
118
|
+
"""Add health checks after init: each returns True/False, or (ok, detail)."""
|
|
119
|
+
client = get_client()
|
|
120
|
+
if client is not None:
|
|
121
|
+
client.health_checks.update(checks)
|
|
122
|
+
client.start()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""ASGI middleware: FastAPI, Starlette, and any ASGI app.
|
|
2
|
+
|
|
3
|
+
from loggerai.asgi import LoggerAIMiddleware
|
|
4
|
+
app.add_middleware(LoggerAIMiddleware)
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from . import context
|
|
9
|
+
from .client import get_client
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _route(scope) -> str | None:
|
|
13
|
+
route = scope.get("route")
|
|
14
|
+
if route is not None:
|
|
15
|
+
path = getattr(route, "path_format", None) or getattr(route, "path", None)
|
|
16
|
+
if path:
|
|
17
|
+
# Routes inside a mounted sub-app are relative to the mount.
|
|
18
|
+
mount = scope.get("app_root_path") or ""
|
|
19
|
+
return (mount.rstrip("/") + path) if mount and not path.startswith(mount) else path
|
|
20
|
+
endpoint = scope.get("endpoint")
|
|
21
|
+
app = scope.get("app")
|
|
22
|
+
if endpoint is not None and app is not None: # older Starlette: find the route by its endpoint
|
|
23
|
+
for r in getattr(app, "routes", []) or []:
|
|
24
|
+
if getattr(r, "endpoint", None) is endpoint:
|
|
25
|
+
return getattr(r, "path_format", None) or getattr(r, "path", None)
|
|
26
|
+
return None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class LoggerAIMiddleware:
|
|
30
|
+
def __init__(self, app):
|
|
31
|
+
self.app = app
|
|
32
|
+
|
|
33
|
+
async def __call__(self, scope, receive, send):
|
|
34
|
+
client = get_client()
|
|
35
|
+
if scope["type"] != "http" or client is None or not client.enabled or client.ignored(scope.get("path", "")):
|
|
36
|
+
return await self.app(scope, receive, send)
|
|
37
|
+
headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers") or []}
|
|
38
|
+
unit = context.Unit("http", scope.get("method", "GET"), context.trace_from(headers.get("traceparent")),
|
|
39
|
+
context.session_from(headers.get("x-loggerai-session")))
|
|
40
|
+
token = context.current.set(unit)
|
|
41
|
+
status = 500
|
|
42
|
+
|
|
43
|
+
async def _send(message):
|
|
44
|
+
nonlocal status
|
|
45
|
+
if message["type"] == "http.response.start":
|
|
46
|
+
status = message["status"]
|
|
47
|
+
await send(message)
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
await self.app(scope, receive, _send)
|
|
51
|
+
except BaseException as e:
|
|
52
|
+
unit.route = unit.route or _route(scope)
|
|
53
|
+
if isinstance(e, Exception):
|
|
54
|
+
client.exception(e, status=500)
|
|
55
|
+
status = 500
|
|
56
|
+
raise
|
|
57
|
+
finally:
|
|
58
|
+
unit.route = unit.route or _route(scope)
|
|
59
|
+
context.current.reset(token)
|
|
60
|
+
client.finish(unit, status)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Celery: every task timed like a request (kind "job"), failures reported.
|
|
2
|
+
|
|
3
|
+
import loggerai, loggerai.celery
|
|
4
|
+
loggerai.init()
|
|
5
|
+
loggerai.celery.instrument()
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from . import context
|
|
10
|
+
from .client import get_client
|
|
11
|
+
|
|
12
|
+
_tokens = {}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def instrument() -> None:
|
|
16
|
+
from celery import signals
|
|
17
|
+
|
|
18
|
+
@signals.task_prerun.connect(weak=False)
|
|
19
|
+
def _start(task_id=None, task=None, **kw):
|
|
20
|
+
client = get_client()
|
|
21
|
+
if client is None or not client.enabled:
|
|
22
|
+
return
|
|
23
|
+
unit = context.Unit("job", "JOB")
|
|
24
|
+
unit.route = getattr(task, "name", None) or "task"
|
|
25
|
+
_tokens[task_id] = (unit, context.current.set(unit))
|
|
26
|
+
|
|
27
|
+
@signals.task_failure.connect(weak=False)
|
|
28
|
+
def _failed(task_id=None, exception=None, **kw):
|
|
29
|
+
client = get_client()
|
|
30
|
+
if client is not None and exception is not None:
|
|
31
|
+
client.exception(exception, status=500)
|
|
32
|
+
|
|
33
|
+
@signals.task_postrun.connect(weak=False)
|
|
34
|
+
def _end(task_id=None, state=None, **kw):
|
|
35
|
+
got = _tokens.pop(task_id, None)
|
|
36
|
+
client = get_client()
|
|
37
|
+
if got is None or client is None:
|
|
38
|
+
return
|
|
39
|
+
unit, token = got
|
|
40
|
+
try:
|
|
41
|
+
context.current.reset(token)
|
|
42
|
+
except ValueError:
|
|
43
|
+
context.current.set(None)
|
|
44
|
+
client.finish(unit, 200 if state == "SUCCESS" else 500)
|