Skip to main content

Production-grade, reusable audit logging for FastAPI applications.

Project description

auditlog-fastapi

Production-grade, reusable audit logging for FastAPI applications.

Features

  • Multi-ORM Support: SQLAlchemy 2 (async), Tortoise ORM, SQLModel, Beanie (MongoDB), and raw asyncpg.
  • Flexible Storage: PostgreSQL, MySQL, MariaDB, SQLite, and MongoDB.
  • Explicit Configuration: Clean API with AuditConfig and configure().
  • Middleware Integration: Capture request/response data automatically.
  • PII Masking: Redact sensitive fields from logs.
  • Context Helpers: Enrich audit logs from route handlers.
  • Lifespan Integration: Automatic startup/shutdown of database connections.
  • Async & Non-blocking: Built with performance and safety in mind.

Installation

# Basic install
pip install auditlog-fastapi

# With SQLAlchemy support (Postgres, MySQL, SQLite)
pip install auditlog-fastapi[sqlalchemy]

# With Tortoise ORM support
pip install auditlog-fastapi[tortoise]

# With SQLModel support
pip install auditlog-fastapi[sqlmodel]

# With MongoDB (Beanie) support
pip install auditlog-fastapi[mongodb]

# With raw asyncpg (PostgreSQL only) support
pip install auditlog-fastapi[asyncpg]

# Everything
pip install auditlog-fastapi[all]

Quick Start (SQLAlchemy + SQLite)

from fastapi import FastAPI
from fastapi_audit_log import AuditMiddleware, AuditConfig, create_audit_lifespan

# 1. Configure the audit log
config = AuditConfig(
    orm="sqlalchemy",
    dsn="sqlite+aiosqlite:///./audit.db",
    table_name="audit_logs",
    auto_create_table=True,
)

# 2. Create lifespan handler
app = FastAPI(lifespan=create_audit_lifespan(config))

# 3. Add middleware
app.add_middleware(
    AuditMiddleware,
    log_request_body=True
)

@app.get("/")
async def root():
    return {"message": "Hello World"}

User Configuration Guide

SQLAlchemy + PostgreSQL

config = AuditConfig(
    orm="sqlalchemy",
    dsn="postgresql+asyncpg://user:pass@localhost:5432/mydb",
    table_name="audit_logs",
    auto_create_table=True,
    sqlalchemy_pool_size=10,
    mask_fields=["password", "token"],
)

SQLAlchemy + MySQL

config = AuditConfig(
    orm="sqlalchemy",
    dsn="mysql+aiomysql://user:pass@localhost:3306/mydb",
    auto_create_table=True,
)

Tortoise ORM + PostgreSQL

config = AuditConfig(
    orm="tortoise",
    dsn="postgres://user:pass@localhost:5432/mydb",
    auto_create_table=True,
)

MongoDB via Beanie

config = AuditConfig(
    orm="beanie",
    dsn="mongodb://localhost:27017",
    mongodb_database="myapp",
    table_name="audit_logs",   # becomes collection name
)

Raw asyncpg (PostgreSQL, maximum performance)

config = AuditConfig(
    orm="asyncpg",
    dsn="postgresql://user:pass@localhost:5432/mydb",
    batch_size=200,
)

Using with Alembic (SQLAlchemy only)

# In alembic/env.py — include audit table in your migrations
from fastapi_audit_log.db.sqlalchemy_table import AuditBase
target_metadata = [YourBase.metadata, AuditBase.metadata]

Enriching Logs from Routes

from fastapi_audit_log import set_audit_action, set_audit_resource, set_audit_extra

@app.post("/items")
async def create_item(item_id: str):
    set_audit_action("item.create")
    set_audit_resource("item", item_id)
    set_audit_extra("metadata", {"source": "admin_panel"})
    return {"status": "ok"}

Retrieving Audit Logs

fastapi-audit-log provides a built-in helper to add a route for querying and filtering your audit logs.

from fastapi import FastAPI
from fastapi_audit_log import add_audit_log_routes

app = FastAPI(...)

# Register the GET /audit-logs route
add_audit_log_routes(
    app,
    path="/audit-logs",      # default
    tags=["Audit Logs"]      # optional tags for OpenAPI
)

Filtering and Pagination

The added route supports several query parameters:

  • Pagination: limit (default 100, max 1000) and offset (default 0).
  • Filters: method, path, status_code, user_id, and action.

Example request: GET /audit-logs?method=POST&status_code=201&limit=20

Configuration Reference (AuditConfig)

Parameter Type Default Description
orm str Required One of: sqlalchemy, tortoise, sqlmodel, beanie, asyncpg.
dsn str Required Connection string for the database.
table_name str "audit_logs" Name of the table or collection.
auto_create_table bool True Whether to create the table on startup.
batch_size int 1 Set > 1 to enable batching (not all backends yet).
mask_fields list[str] [] PII fields to mask in request bodies.
on_storage_error Callable None Optional callback for storage errors.

Development and Examples

To run the examples that require a real database (PostgreSQL, MongoDB, MySQL), you can use the provided Docker Compose file:

docker-compose up -d

This will start:

  • PostgreSQL at localhost:5432 (user: user, pass: pass, db: audit_db)
  • MongoDB at localhost:27017
  • MySQL at localhost:3306 (user: user, pass: pass, db: audit_db)

Running the MongoDB Example

poetry run python examples/beanie_mongodb_usage.py

Running the Asyncpg Example

poetry run python examples/asyncpg_usage.py

Future Features

  • Admin UI: Build a simple web UI for viewing/searching audit logs.
  • Custom Storage Backends: Allow users to plug in custom storage backends (e.g., S3, Redis, external APIs).
  • Event Hooks: Add hooks for pre/post log processing (e.g., for enrichment, notifications).
  • Log Export: Support exporting logs to CSV, JSON, or external log management systems.
  • Retention Policies: Add configurable log retention and automatic cleanup.
  • Multi-Tenancy: Support tenant-aware logging for SaaS apps.
  • Security: Encrypt sensitive log fields at rest, and add role-based access for log viewing.
  • CLI Tooling: Provide CLI commands for log inspection, export, and management.
  • OpenTelemetry Integration: Integrate with OpenTelemetry for distributed tracing and correlation.
  • Documentation: Expand usage examples and add troubleshooting guides.

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

auditlog_fastapi-0.2.0.tar.gz (16.6 kB view details)

Uploaded Source

Built Distribution

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

auditlog_fastapi-0.2.0-py3-none-any.whl (23.5 kB view details)

Uploaded Python 3

File details

Details for the file auditlog_fastapi-0.2.0.tar.gz.

File metadata

  • Download URL: auditlog_fastapi-0.2.0.tar.gz
  • Upload date:
  • Size: 16.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.4 Darwin/25.3.0

File hashes

Hashes for auditlog_fastapi-0.2.0.tar.gz
Algorithm Hash digest
SHA256 9f9d6f0b8e29093a3a46a8fbbabc200799be68cad1f96bcbd89127f77a35b12f
MD5 4e20cd0c4b5799059ba19474c881e8b7
BLAKE2b-256 b4d849b9ce4d8009bc22d677d8dfab7056a599be91b9f3afeae944276f5e9f9e

See more details on using hashes here.

File details

Details for the file auditlog_fastapi-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: auditlog_fastapi-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 23.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.4 Darwin/25.3.0

File hashes

Hashes for auditlog_fastapi-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f53d10d7e4aa2f11272c4145c53694b884f3970d41801256a0e728cfc84ce349
MD5 d8c608667e4af62cd5969fc634a74410
BLAKE2b-256 9d6cd3fb1fee7f512ad9aef4d6c41df9d27f36a9407af906911679104b9440e5

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