Skip to main content

Zero-config auto-instrumentation logging for Python

Project description

autolog

Zero-config auto-instrumentation logging for Python. Drop one line into your entrypoint and every function call gets logged — inputs, outputs, duration, errors, and trace IDs. No changes to your business logic required.


Features

  • Zero-touch mode — patch an entire package at import time with one line
  • Decorator mode — opt-in per function or class
  • Async-native — supports async def, generators, and async generators
  • Sensitive data redaction — automatically masks passwords, tokens, API keys
  • Trace IDs — async-safe per-request correlation via contextvars
  • Structured output — consistent log blocks with inputs, result, duration, error
  • FastAPI & Flask middleware — HTTP request/response logging out of the box
  • Configurable via env vars — no code changes needed to tune behavior
  • Windows-safe — UTF-8 output even on Windows terminals

Installation

pip install autolog

With optional framework support:

pip install "autolog[fastapi]"
pip install "autolog[flask]"

Install from source (development):

git clone https://github.com/YOUR_USERNAME/autolog.git
cd autolog
pip install -e ".[dev]"

Quick Start

Zero-touch — no changes to your code

Create a run.py next to your project and call autolog.install() before anything else:

import autolog
autolog.install(["myapp"])

# your normal entrypoint, completely untouched
from myapp.main import main
main()

Every function in the myapp package is now logged automatically.

Sample output:

[2026-05-07 14:23:01.042] [INFO ] [billing.services.customers.get_customer]
  ▸ trace    : 3f4a1b2c-...
  ▸ inputs   : {"customer_id": "cust_123"}
  ▸ result   : {"id": "cust_123", "name": "Alice"}
  ▸ duration : 0.0031 s
────────────────────────────────────────────────

Usage

Zero-touch (import hook)

import autolog

autolog.install(
    ["myapp", "utils"],   # list of packages to patch
    service="billing",    # optional: label shown in logs
    level="DEBUG",        # optional: minimum log level
    log_file="app.log",   # optional: mirror logs to a file
)

Must be called before importing the packages you want to log.


Decorator — opt-in per function

from autolog import log_function

@log_function
def calculate_tax(amount: float, rate: float) -> float:
    return amount * rate

@log_function
async def fetch_invoice(invoice_id: str):
    ...

# with options
@log_function(service="billing", level="DEBUG", log_file="billing.log")
def process_payment(payload: dict):
    ...

Works with sync, async, generators, and async generators.


Decorator — opt-in per class

from autolog import log_class

@log_class
class InvoiceService:
    def create(self, data): ...
    async def fetch(self, invoice_id): ...
    def _internal(self): ...     # skipped — underscore methods are excluded

Wraps all public methods. Handles @staticmethod, @classmethod, and @property correctly.


Skip specific functions

from autolog import no_log

@no_log
def hot_path():
    """This function will never be wrapped, even inside an auto-patched package."""
    ...

Trace IDs

Correlate all log entries for a single request:

from autolog import new_trace_id, get_trace_id

# at the start of a request / task
trace_id = new_trace_id()   # generates UUID4, stores in ContextVar

# anywhere downstream
trace_id = get_trace_id()   # returns current ID or "-"

Trace IDs are async-safe — each coroutine/task has its own context.


Framework Middleware

FastAPI

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

app = FastAPI()
app.add_middleware(AutoLogMiddleware, service="my-api")

Logs method, path, status code, inputs, and response for every HTTP request. Uses BackgroundTask so logging 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

All options can be set via environment variables — no code changes needed:

Env var Default Description
AUTOLOG_LEVEL INFO Minimum log level (DEBUG, INFO, WARNING, ERROR)
AUTOLOG_FILE Path to mirror logs to a file
AUTOLOG_SERVICE package name Service label shown in log lines
AUTOLOG_DISABLE Set to 1 to disable all wrapping (e.g. in tests)
NO_COLOR Set to 1 to disable ANSI color output

Example:

AUTOLOG_LEVEL=DEBUG AUTOLOG_FILE=app.log python run.py

Sensitive Data Redaction

The following argument names are automatically redacted in both inputs and outputs:

password, passwd, token, secret, key, auth, credential, api_key, apikey, jwt, bearer

def login(username, password):
    ...

# logged as:
# ▸ inputs   : {"username": "alice", "password": "[REDACTED]"}

Redaction is recursive — works inside nested dicts, lists, and tuples.


Log Output Format

Every log entry is a structured block:

[TIMESTAMP] [LEVEL] [module.function]
  ▸ trace    : <uuid>
  ▸ inputs   : {"arg": value, ...}
  ▸ result   : <value>           (on success)
  ▸ error    : <exception repr>  (on failure)
  ▸ duration : 0.0031 s
────────────────────────────────────────────────

Running Tests

pip install -e ".[dev]"
pytest tests/ -v

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-1.0.0.tar.gz (15.3 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-1.0.0-py3-none-any.whl (13.4 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for t_autolog-1.0.0.tar.gz
Algorithm Hash digest
SHA256 7df722b70d111270eba268297a84dd6cf6ba1536f7abf1e97777c627658270cb
MD5 f71c9a4672e5a042f330dec9b473c18a
BLAKE2b-256 4123be74bfc268a0f856aaa5e83aa2fc791104c3bff9c4c8ce6cbce610639d79

See more details on using hashes here.

File details

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

File metadata

  • Download URL: t_autolog-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 13.4 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-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c87a738e029e9a367b402b3ae0141bbba2ac7bd54f98a386ec0278f73a6b66da
MD5 381241c37ab7f6e0e9be434afbe1a145
BLAKE2b-256 3bac797ffea6b9029b970023e3570147d4887ca0405630ecc08632ad672e6ed5

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