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

Uploaded Python 3

File details

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

File metadata

  • Download URL: t_autolog-1.0.1.tar.gz
  • Upload date:
  • Size: 15.4 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.1.tar.gz
Algorithm Hash digest
SHA256 6e79219c9af89bceecfc0472d23e5e6e7ba9441edc9b39e5011cb48c5829cf38
MD5 6d04dc9e76d481d34ef681595682f4d8
BLAKE2b-256 3fce212fefb9499b63762e52bd35b8be9aaca6f0b0298532ea3fe86e340f769d

See more details on using hashes here.

File details

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

File metadata

  • Download URL: t_autolog-1.0.1-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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 a8b41524198b32c63d6ffe2e3c18e89928f6b36bb436bd5bb0c73887f29e50d8
MD5 90a56a1bc3ba21f88dcd390e6a509f55
BLAKE2b-256 d2fbde7b478954a0d59df5b5be009469093d371e2a476e677c51bb81d131dd77

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