Skip to main content

Zero-config auto-instrumentation logging for Python

Project description

autolog

Zero-config, structured, async-safe logging for Python. Drop one line into your entrypoint and every function call gets instrumented — inputs, outputs, duration, errors, traces. No changes to your business logic required.


Features

  • Zero-touchautolog.start() patches your packages at import time
  • Structured outputpretty for dev, json for production (Datadog/Loki/ELK)
  • Async-native — sync, async def, generators, async generators all handled
  • Sensitive data redaction — passwords, tokens, API keys auto-masked
  • Trace IDs + bound contextbind(user_id=42) adds fields to every downstream log
  • Samplingsample=0.01 to log 1% of calls in hot paths
  • Exclude patterns — skip noisy modules without touching their code
  • Per-package levels — DEBUG one package, WARN another
  • Production-safe — rotating files, traceback capture, body-size guards, upstream trace propagation
  • Single CLIautolog run myapp.main, no entrypoint changes needed

Installation

pip install autolog
pip install "autolog[fastapi]"   # FastAPI middleware
pip install "autolog[flask]"     # Flask middleware

Quick start

import autolog
autolog.start()

# everything you import from here on is auto-logged
from myapp.services import process_order
process_order(123)

Output:

[2026-05-07 14:23:01.042] [INFO ] [myapp.services.process_order]
  ▸ trace    : 3f4a1b2c-...
  ▸ inputs   : {"order_id": 123}
  ▸ result   : {"status": "ok"}
  ▸ duration : 0.0031 s

The start() API

start() is the single entry point. All options are optional.

autolog.start(
    packages=["myapp", "utils"],         # None → auto-discover
    exclude=["myapp.hot_path.*"],        # glob patterns to skip
    service="my-api",                    # label in logs
    level={"myapp": "DEBUG", "default": "INFO"},
    format="json",                       # or "pretty" (default)
    log_file="app.log",                  # rotating, 10MB × 5 backups
    sample=0.1,                          # log 10% of calls
    config="pyproject.toml",             # explicit config path
)

Resolution order

kwargs > env vars > [tool.autolog] in pyproject.toml > defaults


Three ways to use it

1. Code

import autolog
autolog.start(packages=["myapp"])

2. Config in pyproject.toml

[tool.autolog]
packages = ["myapp", "utils"]
exclude  = ["myapp.cache.*"]
service  = "my-api"
level    = { myapp = "DEBUG", default = "INFO" }
format   = "json"
log_file = "app.log"
sample   = 0.5
import autolog
autolog.start()   # reads pyproject.toml automatically

3. CLI runner — zero entrypoint changes

autolog run myapp.main
autolog run myapp.main --format json --level DEBUG
autolog run myapp.main --exclude "myapp.hot.*" --sample 0.1
autolog show                              # show resolved config

Bound context fields (structlog-style)

Attach fields once, get them on every log inside the same async context:

from autolog import bind, unbind

async def request_middleware(request, call_next):
    bind(user_id=request.user.id, org_id=request.org.id)
    try:
        return await call_next(request)
    finally:
        unbind()

Now every log inside this request includes user_id and org_id automatically — no need to pass them around.


Decorator mode (opt-in)

from autolog import log, no_log

@log
def calculate(x, y): ...

@log
class OrderService:
    def create(self, data): ...

@log(sample=0.01)         # log 1% of calls
def hot_path(): ...

@no_log                    # never log this one, even if package is auto-instrumented
def secret_op(): ...

@log works on both functions and classes — handles @staticmethod, @classmethod, @property, sync/async/generators automatically.


Trace IDs

Async-safe per-request correlation:

from autolog import new_trace_id, get_trace_id, set_trace_id

new_trace_id()                        # generate UUID4 for this context
set_trace_id("custom-id")             # use an externally-supplied one
get_trace_id()                        # read current

Framework middleware

FastAPI

from fastapi import FastAPI
from autolog.middleware.fastapi import AutoLogMiddleware

app = FastAPI()
app.add_middleware(AutoLogMiddleware, service="my-api")
  • Honors upstream X-Request-ID, X-Trace-ID, traceparent headers
  • Skips body capture for multipart/, octet-stream, text/event-stream, image/*, video/*
  • Truncates large bodies at max_body_bytes (default 64KB) — won't OOM on uploads
  • Async-safe: logging runs in BackgroundTask, never blocks the response

Flask

from flask import Flask
from autolog.middleware.flask import init_autolog

app = Flask(__name__)
init_autolog(app, service="my-api")

Configuration via environment variables

Var Effect
AUTOLOG_LEVEL Override level
AUTOLOG_FILE Mirror logs to file
AUTOLOG_FORMAT pretty or json
AUTOLOG_SERVICE Service name
AUTOLOG_DISABLE=1 Disable all instrumentation
AUTOLOG_FILE_MAX_BYTES Rotation size, default 10MB
AUTOLOG_FILE_BACKUPS Rotated backups, default 5
NO_COLOR=1 Disable ANSI colors

Sensitive data redaction

These keys (and tokens within them) are auto-redacted:

password, passwd, token, secret, auth, credential, apikey, jwt, bearer, api_key, access_token, refresh_token, private_key

Token-aware: apiKey, API_KEY, client.secret all match. keyword, monkey, author do not match (no false positives).


License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

t_autolog-2.2.0.tar.gz (24.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

t_autolog-2.2.0-py3-none-any.whl (21.3 kB view details)

Uploaded Python 3

File details

Details for the file t_autolog-2.2.0.tar.gz.

File metadata

  • Download URL: t_autolog-2.2.0.tar.gz
  • Upload date:
  • Size: 24.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0

File hashes

Hashes for t_autolog-2.2.0.tar.gz
Algorithm Hash digest
SHA256 ca280d2c9b677389f9ea966a07f27c5a7f8cf74f15cd14dd7c68e2a89ca9f201
MD5 eda0800862ff8593d97df126ca002b1f
BLAKE2b-256 bfb6ba19ba538161fa65efe6f614335e4c2f3a7f8fcaba60b3d41d15f3fba8ca

See more details on using hashes here.

File details

Details for the file t_autolog-2.2.0-py3-none-any.whl.

File metadata

  • Download URL: t_autolog-2.2.0-py3-none-any.whl
  • Upload date:
  • Size: 21.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0

File hashes

Hashes for t_autolog-2.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3beea49d2e0ded9123eb8e777368ce70a1f3f5d4dd523e1fe72f78e8cf126898
MD5 37b2ee907db13ca99369df6e8efc7b14
BLAKE2b-256 8595b75996729f1396f9a0ed07aabfe4d85b60a07b8bf60b758670486e528b9d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page