Integrations¶
Redline records what your framework adapter hooks automatically: the ORM, templates, the
cache framework in Django, and so on. Everything else your request does, calling another
service, talking to Redis, querying PostgreSQL without an ORM or dumping data through a
serializer, is covered by contrib integrations in redline_core.contrib.
They share a few rules:
- Opt-in. Nothing is patched until you call the
instrument_*function. They are never imported byimport redline_core, so unused ones cost nothing. - Idempotent. Call each once at startup (twice is harmless). Each has an
uninstrument_*twin that restores the original. - Free outside a request. Outside a traced request each wrapper is one
ContextVar.get(). - Redacted. URLs, keys and parameters pass through the same redaction as everything else.
| Library | Call | Records | Extra |
|---|---|---|---|
| SQLAlchemy | instrument_engine(engine) |
sql, transaction, pool_wait spans |
sqlalchemy |
| httpx | instrument_httpx() |
http_out spans |
httpx |
| requests | instrument_requests() |
http_out spans |
requests |
| boto3 | instrument_boto3() |
http_out spans per SDK operation |
boto3 |
| redis-py | instrument_redis() |
cache spans |
redis |
| pymongo | instrument_pymongo() |
custom spans per collection call (client="mongodb") |
none |
| kafka-python | instrument_kafka() |
custom publish spans (client="kafka") |
none |
| pika | instrument_pika() |
custom publish spans (client="amqp") |
none |
| Google Cloud Storage | instrument_google_cloud_storage() |
custom upload/download spans (client="gcs") |
none |
| Azure Blob Storage | instrument_azure_blob() |
custom upload/download/delete spans (client="azure_blob") |
none |
| asyncpg | instrument_asyncpg() |
sql spans |
asyncpg |
| psycopg 3 | instrument_psycopg() |
sql spans |
psycopg |
| Raw DB-API driver | instrument_dbapi(module) |
sql spans (source="raw_cursor") |
any DB-API driver |
| Threads and pools | instrument_threads() |
carries the request into Thread and ThreadPoolExecutor work; spans get data["thread"] |
none |
| Marshmallow | instrument_marshmallow() |
serializer spans |
none |
| Strawberry | RedlineExtension |
resolver spans |
strawberry |
| Graphene | RedlineMiddleware |
resolver spans |
graphene |
The extras install the third-party library at a compatible version, for example
pip install "redline-core[redis] @ git+https://github.com/Pythondeveloper6/redline#subdirectory=packages/redline-core".
The adapters re-export instrument_httpx (and instrument_requests for Flask) so older
imports keep working.
SQLAlchemy¶
from redline_core.contrib.sqlalchemy import instrument_engine
instrument_engine(engine) # sync or async engine
The FastAPI, Flask and Litestar adapters call this for the engines you pass them. Use it directly when you build an engine Redline does not know about. Beyond statement, parameters, duration and callsite it records:
transactionspans from the begin, commit and rollback events, with the outcome, the number of queries inside and the number of outbound HTTP calls made while the transaction was open. Empty transactions and control statements such asSAVEPOINTare not recorded. See Transactions and locks.pool_waitspans when checking a connection out of the pool takes 1 ms or more, with the pool size and how many connections were already checked out.- The SQLAlchemy fix suggester and the EXPLAIN executor
(
SQLAlchemyFixSuggester,explain_executor_factory).
httpx¶
from redline_core.contrib.httpx import instrument_httpx
instrument_httpx() # every httpx.Client / AsyncClient call becomes an http_out span
A span records method, URL (redacted), status and duration. The span name is
GET host/path. This feeds the External calls page and the
slow_external, duplicate_external and retry_storm detectors.
requests¶
from redline_core.contrib.requests import instrument_requests
instrument_requests() # patches requests.Session.send
Same data as httpx. Because requests is synchronous, calling it inside an async def
handler also blocks the event loop; see Blocking in async.
boto3¶
Records one http_out span for each botocore client operation. Span names and synthetic URLs
contain only the service and operation (for example, AWS s3 GetObject and
https://s3.amazonaws.com/__sdk__/GetObject). Status and duration are recorded; API arguments,
response data, bucket and object keys, credentials, presigned URLs, and error messages are not
captured. If HTTP-level instrumentation also observes the SDK's network request, both spans may
appear: the SDK span measures the whole operation, while the HTTP span measures its network call.
instrument_boto3() returns False when botocore is unavailable.
Redis¶
Wraps Redis.execute_command for both the sync client and redis.asyncio, and
Pipeline.execute. Each command becomes a cache span with op (the command), key
(capped at 200 characters), backend (redis) and, for read commands, hit (GET, GETEX, GETDEL,
HGET, MGET, HMGET, LINDEX: a None result is a miss). A pipeline is one span
(op="pipeline"); the commands queued on it are not recorded individually, and spans
without a key are not included in the cache statistics.
Django's cache framework (including a Redis cache backend) is already recorded by
django-redline; use this when you talk to Redis directly, from Flask, FastAPI or
Litestar, or from Django code that bypasses django.core.cache.
asyncpg¶
For apps that use asyncpg without an ORM. Wraps Connection.execute, fetch, fetchrow,
fetchval and executemany; pool methods delegate to these, so pooled connections are
covered. Statements are recorded in asyncpg's $1 placeholder style. Row counts are filled
in where the result exposes them, which enables the
large-result detectors.
psycopg 3¶
For psycopg 3 used directly, sync or async cursors. The patch is process-wide (a connection argument is accepted and ignored). If you use SQLAlchemy with the psycopg driver you do not need this: SQLAlchemy's events already see those queries, and patching both would record each query twice.
One path per query
Use exactly one capture path per database driver: the ORM's (Django, SQLAlchemy) or the driver-level one (asyncpg, psycopg). If you instrument SQLAlchemy and asyncpg and use SQLAlchemy's asyncpg dialect, every query is recorded twice.
Raw DB-API cursors¶
SQL that bypasses the engine is recorded too. With an instrumented SQLAlchemy engine,
engine.raw_connection() called from your code returns a thin proxy: cursor().execute,
executemany and callproc become sql spans with source="raw_cursor". An executemany
is one span with a batch_size, not one span per row.
For a driver used with no engine at all, opt in once at startup:
import sqlite3
from redline_core.contrib.dbapi import instrument_dbapi
instrument_dbapi(sqlite3) # patches sqlite3.connect; undo with uninstrument_dbapi(sqlite3)
Limits: statements run through connection.connection.cursor() of a SQLAlchemy
Connection and connections opened before instrument_dbapi was called are not recorded.
redline instrumentation lists every loaded raw driver (psycopg2, pymysql, MySQLdb, pyodbc,
pymssql, oracledb, cx_Oracle) as dbapi:<driver>: active or inactive. Inactive means SQL
sent through that driver's own connect() is not recorded. auto_instrument never wraps a
driver, because SQLAlchemy calls the same connect() and the SQL would be recorded twice.
Marshmallow¶
Patches Schema.dump. Only the outermost dump becomes a serializer span; nested
schemas (fields.Nested) are part of their parent's time. Feeds the
slow serializer detector. Marshmallow has no extra: the call
returns False if marshmallow is not installed.
Data stores, queues and object storage¶
from redline_core.contrib.pymongo import instrument_pymongo
from redline_core.contrib.kafka import instrument_kafka
from redline_core.contrib.pika import instrument_pika
from redline_core.contrib.google_cloud_storage import instrument_google_cloud_storage
from redline_core.contrib.azure_blob import instrument_azure_blob
These record custom spans built with instrument_client_method.
Each span has client, op, target, payload_bytes and error in its data. Every function
imports its library only when called and returns False if it is not installed, so an app
without the library is unaffected. Filters, documents, message keys and bodies, object names,
URLs and credentials are never captured, and an error is recorded as its class name.
| Integration | What a span covers | Target | Size |
|---|---|---|---|
| pymongo | Collection writes, find_one, count_documents, distinct, bulk_write, and each network batch of a find() cursor (op="find") |
database.collection |
none |
| kafka-python | KafkaProducer.send (op="publish"). send only enqueues, so the span is the time the caller waited, not delivery |
topic | value, when bytes |
| pika | BlockingChannel.basic_publish (op="publish") |
exchange/routing_key |
body |
| Google Cloud Storage | Blob.upload_from_* and download_* |
bucket | upload data (upload_from_string) and downloaded bytes or text |
| Azure Blob Storage | BlobClient.upload_blob, download_blob, delete_blob, sync and aio. download_blob covers starting the download; the stream is read later |
container | upload data |
For any other client, wrap it yourself with instrument_client_method
(Extending). auto_instrument="on" also instruments
these when they are installed; the default "warn" lists them if installed and inactive.
Asynchronous drivers (motor, aiokafka) are not covered; wrap their coroutine methods with the helper.
Threads and pools¶
Not a client but a gap in what is attributed: SQL, cache and HTTP calls made on a plain
threading.Thread or a ThreadPoolExecutor worker belong to no request, because those
threads do not inherit contextvars. instrument_threads() patches ThreadPoolExecutor.submit
and Thread.start so the work runs in a copy of the request's context. The spans appear under
the request, each with the thread's name in data["thread"]. It is process-wide, reversible
with uninstrument_threads(), and never enabled by auto_instrument. Work that outlives the
request is not recorded. Details and limits: Work on threads and pools.
GraphQL¶
Strawberry and Graphene resolvers are described on their own page: GraphQL.
Writing your own¶
The building blocks are public. redline_core.record_span and redline_core.record_query
add a span to the current request from any code:
import time
from redline_core import record_span
start = time.perf_counter()
result = my_client.call()
# record_span(kind, name, start, duration_in_seconds, data)
record_span("http_out", "POST payments.example/charge", start,
time.perf_counter() - start, {"status": 200, "method": "POST"})
For plain timing of your own code, use redline_core.span (Custom spans).
For a full integration with its own fix suggestions see Extending.
Zero-config coverage¶
httpx, requests, Redis and boto3 capture is opt-in, so an installed library can silently go
unrecorded. The auto_instrument setting (all four adapters apply it when Redline installs)
decides what happens:
| Value | Behaviour |
|---|---|
"warn" (default) |
Log one warning listing installed but uninstrumented integrations and how to enable them. Nothing is patched. |
"on" |
Instrument every installed supported integration at install time. |
"off" |
Do nothing. |
Provider libraries are only imported when being instrumented. A failure to instrument one
integration is logged and never stops startup. Calling instrument_httpx() yourself still
works and silences the warning for that integration.
RQ¶
from redline_core.contrib.rq import instrument_rq
integration = instrument_rq(recorder) # web process and worker process
# integration.uninstall() restores RQ
Install with pip install "redline-core[rq]". Enqueueing inside a traced request stores its
trace context in job.meta["redline"]; Job.perform then records the job (name, id, queue,
outcome, SQL and other spans) linked to that request through parent_trace_id and the W3C
trace id. Arguments and results are not captured. Pass task_filter=lambda name: ... to
limit which jobs are recorded.
Dramatiq¶
from redline_core.contrib.dramatiq import instrument_dramatiq
instrument_dramatiq(broker, recorder) # in the web process and in the worker process
Install with pip install "redline-core[dramatiq]". A middleware carries the trace context
in message.options["redline"] and records each processed message as a job (the retry count
is the attempt). Works with any broker; the tests use StubBroker.
FastAPI and Starlette background tasks¶
BackgroundTasks.add_task / BackgroundTask run after the response was sent, when the
request trace has already been stored. fastapi_redline.install records each as its own job
(job.queue = starlette.background), linked to the request that created it. Other
Starlette apps can call redline_core.contrib.starlette_background.instrument_background_tasks(recorder).
Checking integration coverage¶
Open Analysis → Recording health (or GET api/analysis/health) to distinguish whether
an optional provider is installed, loaded in this process and instrumented. The check
never imports providers or enables hooks. An inactive hook means those calls may be
missing; an active hook still does not prove calls occurred or cover other workers.
HTTPX, requests, Redis and boto3 are explicit opt-ins unless auto_instrument is "on"; the default "warn" logs which ones are installed but inactive.
SDK operation spans use a SDK:<operation> method and a synthetic service URL. Because
resource identity and individual retry attempts are deliberately omitted, these spans
contribute latency/error/count totals but do not establish duplicate calls or retry
storms. This avoids treating reads of different object keys as identical requests.