Python
Send logs, exceptions, metrics, heartbeats and deployments from Python with the incidion package.
The incidion package works on Python 3.9 and newer and has no required dependencies. Logs and metrics are queued in memory and sent by a background thread; your code never waits for the network.
Install
The package is not on PyPI yet. Install it from GitHub:
pip install "incidion @ git+https://github.com/nad3rk/incidion.git#subdirectory=backend/incidion-sdk"
# With OpenTelemetry trace correlation (adds opentelemetry-api)
pip install "incidion[otel] @ git+https://github.com/nad3rk/incidion.git#subdirectory=backend/incidion-sdk"
The same line works in requirements.txt. A release on PyPI (pip install incidion) follows.
Quick start
from incidion import Incidion
client = Incidion(api_key="pk_your_public_key", service="checkout-api")
client.info("User signed up", metadata={"plan": "pro"})
client.metric("queue.depth", 42, tags={"queue": "emails"})
try:
charge_card(order)
except Exception as exc:
client.error(exc) # level error, with error_type, error_message and stack_trace
client.close() runs automatically when the interpreter exits. Call client.flush() to send now.
Configuration
Every option can also come from an environment variable; an explicit argument wins.
| Parameter | Env var | Default | Description |
|---|---|---|---|
api_key |
INCIDION_API_KEY |
required unless secret_key is set |
Public key pk_...: logs, metrics, heartbeats by monitor UUID |
secret_key |
INCIDION_SECRET_KEY |
api_key if that is an sk_ key |
Secret key sk_...: deployments only |
project_id |
INCIDION_PROJECT_ID |
None |
Project UUID, needed for deployments |
base_url |
INCIDION_BASE_URL |
https://ingest.incidion.dev |
Ingest host (logs, metrics) |
api_url |
INCIDION_API_URL |
derived | API host (heartbeats, deployments), see below |
service |
INCIDION_SERVICE |
None |
Default service of every log |
environment_id |
INCIDION_ENVIRONMENT_ID |
None |
UUID of an Incidion environment, sent with every batch |
release |
INCIDION_RELEASE |
None |
App version, added to every log’s attributes as release |
before_send |
None |
callable(entry) -> entry or None |
|
sample_rate |
1.0 |
Fraction of logs below error that are kept (0.0 to 1.0) |
|
flush_interval |
5.0 |
Seconds between background flushes | |
batch_size |
50 |
Most entries per request; a full batch is sent at once | |
max_queue_size |
10000 |
Most logs and metric values waiting; the oldest are dropped first | |
max_retries |
5 |
Retries of a batch after 429, 503, 502, 504 or network errors | |
max_retry_delay |
300.0 |
Longest wait in seconds before a retry, Retry-After included |
|
debug |
False |
SDK diagnostics on the incidion.client logger, printed to stderr |
api_url defaults to https://api.incidion.dev for the default ingest, to https://staging.incidion.dev for https://ingest.staging.incidion.dev, and to base_url otherwise (self-hosted: one host serves both). A trailing /api/v1 is removed.
Logs go to the environment of the key unless environment_id is set. The constructor raises ValueError when there is no key, when environment_id is not a UUID, or when sample_rate is outside 0.0 to 1.0.
# Everything from the environment
INCIDION_API_KEY=pk_your_public_key
INCIDION_SERVICE=checkout-api
INCIDION_RELEASE=1.4.2
client = Incidion() # reads the variables above
Keys
# In your app: the public key only
client = Incidion(api_key="pk_...", service="api")
# In CI, for deployments: the secret key alone is enough
ci = Incidion(secret_key="sk_...", project_id="your-project-uuid")
A client without a pk_ api_key drops logs and metrics with a single warning. An sk_ key passed as api_key still works for deployments, but the client warns at startup and drops logs and metrics, because the ingest answers secret keys with 401. Never ship the sk_ key in a desktop or mobile app.
Logs
client.debug("Cache miss", metadata={"key": "user:42"})
client.info("Order placed", metadata={"order_id": "ORD-123", "total": 49.99})
client.warning("Disk space low")
client.error("Connection failed") # a message
client.error(ValueError("bad input")) # an exception: same as capture_exception
client.critical("Service unreachable")
client.log("Custom level", level="info")
metadata becomes the log’s attributes, which you can search and filter on. Keyword arguments fill log columns: service, logger, request_id, trace_id, span_id, user_id, session_id, http_method, http_path, http_status, http_duration_ms, ip_address, user_agent, error_type, error_message, stack_trace, file_name, line_number, function_name. Unknown keywords are ignored.
client.info(
"GET /orders",
request_id="req-789",
http_method="GET",
http_path="/orders",
http_status=200,
http_duration_ms=42,
)
Every log also carries timestamp (UTC), level, sdk_name (incidion-python), sdk_version, and the attributes hostname, pid, python_version and os.
Exceptions
try:
process_payment()
except Exception:
client.capture_exception() # the exception being handled
# or: client.capture_exception(exc, metadata={"order_id": "ORD-123"})
capture_exception logs at level error with error_type (the class name), error_message and stack_trace (the full traceback).
Context: tags, user, release, environment
client.set_tags({"region": "eu-west", "tier": "web"}) # merged into every log's attributes
client.set_tag("canary", True)
client.set_tag("canary", None) # removes one tag
client.set_tags(None) # removes all
client.set_user("user-42") # user_id of every following log
client.set_user(None) # clears it
release and environment_id are set once on the client (or with INCIDION_RELEASE and INCIDION_ENVIRONMENT_ID). Per-call values win: metadata over tags, release and the automatic attributes; a user_id= argument over set_user. Tags apply to logs, not to metrics.
before_send and sampling
before_send runs on the finished entry (a dict, exactly as it will be sent) right before it is queued. Return it, changed or not, to send it, or None to drop it.
import re
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
def scrub(entry):
if entry.get("http_path") == "/health":
return None # drop
entry["message"] = EMAIL.sub("[email]", entry["message"])
for key, value in entry.get("attributes", {}).items():
if isinstance(value, str):
entry["attributes"][key] = EMAIL.sub("[email]", value)
return entry
client = Incidion(api_key="pk_...", before_send=scrub, sample_rate=0.1)
If the callback raises, or returns something that is not a dict, the entry is sent unchanged; the first failure is logged as an error on incidion.client. before_send applies to logs, not to metrics.
sample_rate=0.1 keeps 10% of debug, info and warning logs. error and critical logs, captured exceptions included, are always kept.
OpenTelemetry trace correlation
With opentelemetry-api installed (incidion[otel]), a log written while a span is active gets that span’s trace_id and span_id (lowercase hex), so logs and traces link up. Explicit trace_id= and span_id= arguments win. Without the package nothing changes.
from opentelemetry import trace
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("checkout"):
client.info("Charging card") # carries the span's trace_id and span_id
Incidion stores logs, not traces. To send logs from an existing OpenTelemetry setup instead of the SDK, see OpenTelemetry.
Python logging
IncidionHandler forwards standard logging records. It sets logger, file_name, line_number and function_name and, when the record has exc_info (logger.exception(...)), error_type, error_message and stack_trace.
import logging
from incidion import Incidion, IncidionHandler
client = Incidion(api_key="pk_...", service="worker")
logging.getLogger().addHandler(IncidionHandler(client, level=logging.WARNING))
log = logging.getLogger("billing")
log.warning("Invoice retry for %s", invoice_id)
try:
1 / 0
except ZeroDivisionError:
log.exception("Invoice failed") # with the stack trace
# extra= fields are sent too
log.error("Payment failed", extra={"user_id": "u_123", "request_id": rid, "gateway": "stripe"})
Fields passed with extra= are forwarded: log columns (user_id, request_id, trace_id, http_status, …) land in those columns, everything else in the log’s attributes (above, gateway). Names starting with _ are left out. Values are made JSON-safe; objects other than common scalars (UUID, datetime, Decimal, …) are sent as <ClassName>.
IncidionHandler(client, level=logging.ERROR, service=None): the default level is ERROR; service overrides the client’s service for these logs. Levels map to debug, info, warning, error and critical. The SDK’s own messages (the incidion loggers) are never forwarded, so the handler can sit on the root logger at any level.
Django
Create the client once and hand the handler to LOGGING through a factory:
# myproject/incidion_setup.py
from incidion import Incidion, IncidionHandler
client = Incidion(service="web") # INCIDION_API_KEY, INCIDION_RELEASE from the environment
def handler():
return IncidionHandler(client)
# settings.py
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"console": {"class": "logging.StreamHandler"},
"incidion": {"()": "myproject.incidion_setup.handler", "level": "WARNING"},
},
"root": {"handlers": ["console", "incidion"], "level": "INFO"},
"loggers": {
# 5xx responses and unhandled exceptions, with the traceback
"django.request": {"handlers": ["console", "incidion"], "level": "WARNING", "propagate": False},
},
}
The background thread does not survive fork(). With gunicorn --preload (or any server that forks after importing your app), create the client in each worker, for example in gunicorn’s post_fork hook, not at import time in the master.
FastAPI
import time
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from incidion import Incidion
client = Incidion(service="api")
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
client.close() # deliver what is queued before the worker exits
app = FastAPI(lifespan=lifespan)
@app.middleware("http")
async def incidion_requests(request: Request, call_next):
started = time.perf_counter()
fields = {
"http_method": request.method,
"http_path": request.url.path,
"request_id": request.headers.get("x-request-id"),
"user_agent": request.headers.get("user-agent"),
}
try:
response = await call_next(request)
except Exception as exc:
client.capture_exception(exc, http_status=500, **fields)
raise
level = "error" if response.status_code >= 500 else "info"
client.log(
f"{request.method} {request.url.path}",
level=level,
http_status=response.status_code,
http_duration_ms=round((time.perf_counter() - started) * 1000),
**fields,
)
return response
Logging calls only queue the entry, so they are safe in async code.
Flask
from flask import Flask
from incidion import Incidion, IncidionHandler
client = Incidion(service="web")
app = Flask(__name__)
app.logger.addHandler(IncidionHandler(client))
Flask logs every unhandled exception on app.logger with exc_info, so the handler sends each one with its traceback. To log requests as well, call client.info(...) with the http_* fields from an after_request function, as in the FastAPI middleware above.
Metrics
client.metric("cpu.usage", 63.5, unit="percent")
client.metric("queue.depth", 120, tags={"queue": "emails"})
client.metric("job.duration", 8.2, unit="s", tags={"job": "backup"}, host="worker-3")
metric(name, value, unit=None, tags=None, host=None) queues one value. Values are sent in batches, one request per (host, tags) pair, with the same retries as logs. host defaults to the machine’s hostname. A value that is not a finite number (NaN, infinity, a string, a bool) is dropped. The values of one request share one timestamp, the time of the first one.
Heartbeats
Create a heartbeat monitor and copy its URL (or its hb_ token). Heartbeat URLs need no API key.
# backup.py, run by cron: 0 3 * * * /usr/bin/python3 /opt/jobs/backup.py
import os
from incidion import Incidion, heartbeat
client = Incidion(service="backup")
PING = os.environ["BACKUP_HEARTBEAT_URL"] # https://api.incidion.dev/api/v1/heartbeat/hb_.../
@heartbeat(client, monitor_id=PING, send_start=True)
def main():
run_backup() # "up" on success; "down" with the error on an exception (re-raised)
if __name__ == "__main__":
main() # close() runs at exit and delivers the logs
@heartbeat(client, monitor_id, *, send_start=False, capture_output=False): send_start=True reports the start first, so Incidion records the run time. On an exception it pings down with "<Type>: <message>", logs the exception with capture_exception and re-raises. capture_output=True puts the return value into the up message.
By hand:
client.send_heartbeat_start(PING) # job started
client.send_heartbeat(PING) # up
client.send_heartbeat(PING, status="down", message="Backup failed")
client.send_heartbeat(PING, status="degraded")
Both run synchronously (10 second timeout) and return True when Incidion recorded the ping. Failures are logged on incidion.client, never raised. A monitor UUID still works (the legacy route, sent with api_key), but the URL is preferred. More on monitors: Heartbeats.
Deployments from CI
Deployments need the project’s secret key (secret_key or INCIDION_SECRET_KEY), project_id, and the Pro plan or higher. Keep the secret key in your CI secrets.
# scripts/deploy.py: python scripts/deploy.py ./deploy.sh production
import os
import subprocess
import sys
from incidion import Incidion, IncidionError
client = Incidion() # INCIDION_SECRET_KEY and INCIDION_PROJECT_ID from the CI secrets
sha = os.environ["GITHUB_SHA"]
repo = f"{os.environ['GITHUB_SERVER_URL']}/{os.environ['GITHUB_REPOSITORY']}"
deployment_id = None
try:
deployment_id = client.deployment_start(
sha[:7],
environment=sys.argv[2], # slug of an Incidion environment
commit_hash=sha,
branch=os.environ["GITHUB_REF_NAME"],
run_url=f"{repo}/actions/runs/{os.environ['GITHUB_RUN_ID']}",
repository_url=repo,
deployed_by_name=os.environ["GITHUB_ACTOR"],
)
except IncidionError as exc: # PlanLimitError included
print(f"Incidion: deployment not recorded: {exc}", file=sys.stderr)
result = subprocess.run([sys.argv[1]])
if deployment_id:
ok = result.returncode == 0
client.deployment_finish(
deployment_id,
"success" if ok else "failed",
error_message=None if ok else f"exit code {result.returncode}",
)
sys.exit(result.returncode)
# .github/workflows/deploy.yml
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install "incidion @ git+https://github.com/nad3rk/incidion.git#subdirectory=backend/incidion-sdk"
- run: python scripts/deploy.py ./deploy.sh production
env:
INCIDION_SECRET_KEY: ${{ secrets.INCIDION_SECRET_KEY }}
INCIDION_PROJECT_ID: ${{ vars.INCIDION_PROJECT_ID }}
deployment_start(version, *, environment, commit_hash, commit_message, branch, run_url, repository_url, changes, deployed_by_name, trigger) returns the deployment id; trigger is "ci" (the server’s default), "manual" or "rollback"; changes is a list such as [{"type": "feat", "message": "faster checkout"}]. deployment_finish(deployment_id, status="success", *, error_message=None, build_steps=None) takes "success", "failed" or "rolled_back" and returns the updated deployment; build_steps is a list such as [{"name": "Test", "status": "success", "duration_seconds": 82}]. Both are synchronous (15 second timeout). See Deployments.
Flush and close
client.flush() # send what is queued now
dropped = client.close(timeout=5.0)
close() also runs at interpreter exit (atexit). Call it yourself where atexit does not run or comes too late:
- Serverless (AWS Lambda, Cloud Functions): the process is frozen after the handler returns. Call
client.flush()at the end of every invocation. - Workers (Celery, RQ): call
client.close()on worker shutdown; processes killed withSIGKILLor ended withos._exitskipatexit. - CLI scripts and cron jobs: nothing to do when the script ends normally. Or use the client as a context manager:
with Incidion(api_key="pk_...") as client:
client.info("Starting import")
run_import()
# flushed and closed here
Delivery
- Logs and metrics are sent every
flush_intervalseconds, or at once whenbatch_sizeentries wait. Requests carry at mostbatch_sizeentries and wait up to 30 seconds for the answer. 429(rate limit or daily quota) and503(storage unavailable): the batch stays queued and nothing is sent until the server’sRetry-After, capped bymax_retry_delay.- Network errors,
502and504: sent again after 2, 4, 8, 16, then 30 seconds. - A batch is retried at most
max_retriestimes, then dropped with an error. 413: the batch is sent again in halves.- Rows the ingest rejects one by one (for example an invalid
level) are logged onincidion.clientwith their index and reason (the first 5). Any other4xxdrops the batch and logs the answer. - More than
max_queue_sizelogs and metric values waiting: the oldest are dropped first.
close(timeout=5.0) waits at most timeout seconds in total: first for a batch being sent, then for one last attempt at everything still queued, even while the API asked to wait. What is not delivered by then is dropped with one error, and close() returns that number (logs plus metric values). Logging after close() is ignored with a warning.
Errors
| Call | On failure |
|---|---|
Incidion(...) |
ValueError: no key, environment_id not a UUID, sample_rate outside 0.0 to 1.0, before_send not callable |
Logs, metrics, flush |
Never raise; problems are logged on incidion.client |
send_heartbeat, send_heartbeat_start |
Never raise; return False |
deployment_start, deployment_finish |
PlanLimitError or IncidionError |
from incidion import IncidionError, PlanLimitError
try:
client.deployment_start("1.4.2", environment="production")
except PlanLimitError as err: # HTTP 403 PlanLimitExceeded
print(err.message, err.plan_limit.get("upgrade_required"))
except IncidionError as err: # anything else
print(err.status, err.code, err.message, err.details)
PlanLimitError is a subclass of IncidionError. IncidionError covers a missing project_id or secret key and a pk_ key given as secret_key (raised before any request), an invalid key (401), validation errors (400, field errors in err.details), other HTTP errors and network errors. err.status is None when there was no answer. deployment_finish raises ValueError for a status other than success, failed or rolled_back.
Troubleshooting
Logs never arrive and the log says the ingest returned 401, or the client warns that api_key is a secret key. Logs and metrics need the public key (pk_...). Pass the sk_ key as secret_key and the pk_ key as api_key.
PlanLimitError (HTTP 403 PlanLimitExceeded) from deployment_start. The organization is on the Free plan; deployments need Pro or higher. See Plans and Limits.
Nothing arrives from a short script, a Lambda function or a worker. The process ended before the background thread sent the batch. Call client.flush() or client.close() before it exits (see Flush and close).
Still nothing. Turn on debug=True: the incidion.client logger then prints each request with its HTTP status and every batch flushed, besides the warnings and errors it always logs (rejected rows, retries, 429 quota answers, dropped batches). Without any logging configuration Python prints those warnings and errors to stderr.