Skip to main content

Async MongoDB-backed audit log library with create, list, and pagination support.

Project description

library.audit-log

Lightweight async audit log library for MongoDB. It supports:

  • create audit log records
  • query audit log records as a list
  • query audit log records with pagination
  • custom MongoDB queries with automatic ISO datetime conversion

Installation

pip install library.audit-log

For local development inside this repository:

cd audit-log-lib
python -m build

Install development dependencies:

pip install -e .[dev]

Configuration

The library connects to MongoDB using a connection string.

Required config

  • connection_string: MongoDB connection string

Example:

MONGO_CONNECTION_STRING=mongodb://username:password@localhost:27017/audit_db?authSource=admin

If your MongoDB server has authentication enabled, the connection string must include valid credentials. A URI like mongodb://localhost:27017/audit_db will connect, but writes will fail with Command insert requires authentication.

Optional config

  • database_name: Explicit database name. If omitted, the library uses the database from the connection string.
  • collection_name: MongoDB collection name. Default is audit_trails.

Data model

Each audit log record supports these fields:

{
  "owner_uid": "company-001",
  "actor": {
    "username": "alice",
    "name": "Alice",
    "role": "admin"
  },
  "entity": {
    "uid": "order-123",
    "name": "Order #123"
  },
  "entity_type": "order",
  "action_type": "create"
}

The library automatically adds:

  • uid
  • created_at

Basic usage

import os

from audit_log_lib import AuditLogCreate, AuditLogRepository


def require_env(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"Missing required environment variable: {name}")
    return value


repository = AuditLogRepository(
    connection_string=require_env("MONGO_CONNECTION_STRING"),
    database_name="audit_db",
    collection_name="audit_trails",
)


async def create_log():
    result = await repository.create(
        obj_in=AuditLogCreate(
            owner_uid="company-001",
            actor={
                "username": "alice",
                "name": "Alice",
                "role": "admin",
            },
            entity={
                "uid": "order-123",
                "name": "Order #123",
            },
            entity_type="order",
            action_type="create",
        )
    )
    return result

Get by uid

async def get_one(uid: str):
    return await repository.get_by_uid(uid=uid)

Get as list

from datetime import UTC, datetime, timedelta


async def get_logs():
    return await repository.get_by_owner(
        owner_uid="company-001",
        username="alice",
        start_date=datetime.now(UTC) - timedelta(days=7),
        end_date=datetime.now(UTC),
        search_keyword="order",
        skip=0,
        limit=50,
    )

Get with pagination

If you want both items and total, use the paginated methods.

async def get_logs_paginated():
    result = await repository.list_paginated_by_owner(
        owner_uid="company-001",
        entity_type="order",
        action_type="create",
        skip=0,
        limit=20,
    )

    print(result.total)
    print(result.items)
    return result

Custom query with pagination

async def get_custom_logs():
    return await repository.list_custom_paginated(
        owner_uid="company-001",
        custom_query={
            "entity_type": "order",
            "created_at": {
                "$gte": "2024-01-01T00:00:00.000Z",
                "$lte": "2024-12-31T23:59:59.000Z",
            },
            "$or": [
                {"actor.username": "alice"},
                {"entity.name": {"$regex": "Order", "$options": "i"}},
            ],
        },
        skip=0,
        limit=20,
    )

The library will automatically convert ISO datetime strings under $gte, $lte, $gt, and $lt into Python datetime objects before sending the query to MongoDB.

FastAPI example

import os

from fastapi import FastAPI
from audit_log_lib import AuditLogCreate, AuditLogRepository


app = FastAPI()

audit_repository = AuditLogRepository(
    connection_string=require_env("MONGO_CONNECTION_STRING"),
    database_name="audit_db",
)


@app.post("/audit")
async def create_audit_log():
    return await audit_repository.create(
        obj_in=AuditLogCreate(
            owner_uid="company-001",
            actor={"username": "alice"},
            entity={"uid": "item-001", "name": "Item 001"},
            entity_type="item",
            action_type="create",
        )
    )

See runnable examples in:

  • examples/basic_usage.py
  • examples/fastapi_example.py

Tests

Run tests:

cd audit-log-lib
pytest

Main coverage included in tests/test_repository.py:

  • create log
  • get by uid
  • get list by owner
  • pagination with total/items
  • custom query with ISO datetime conversion

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

library_audit_log-0.1.2.tar.gz (6.2 kB view details)

Uploaded Source

Built Distribution

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

library_audit_log-0.1.2-py3-none-any.whl (5.4 kB view details)

Uploaded Python 3

File details

Details for the file library_audit_log-0.1.2.tar.gz.

File metadata

  • Download URL: library_audit_log-0.1.2.tar.gz
  • Upload date:
  • Size: 6.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for library_audit_log-0.1.2.tar.gz
Algorithm Hash digest
SHA256 d88ecac2bf98d85771f09c9e214e6ca69e9608ae100314e50723d91db9ed590c
MD5 59829244e96321816dc81e62b6c91ce4
BLAKE2b-256 fb21f921133232a5e0c2ae2a405007a599cccec4a2ca05bfde41c4bd071e48a1

See more details on using hashes here.

File details

Details for the file library_audit_log-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for library_audit_log-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 a5e0c9950b93ee41dfff1af0a149de01643b5f3a26edf48f10277617fc206d9e
MD5 d7d97d9e08c5e557ddd83c1497b53cb6
BLAKE2b-256 4b43e0684c614cc910401d393fbf3acbd3e9489a3c91f0b9d6bbd364393fe0bf

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