Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

django-sec-audit

PyPI version Python versions License GitHub

Structured security and audit logging for Django, emitting OpenTelemetry LogRecord-shaped JSONL events.

Captures HTTP request/response metadata, auth events (login, logout, failures), model changes (via django-auditlog), and DRF view metadata out of the box.

Features

  • HTTP middleware — automatic capture of requests, responses, status codes, timing, client IP, routes, DRF metadata
  • Auth signals — automatic logging of user_logged_in, user_logged_out, user_login_failed
  • Model forwarding — forward django-auditlog entries as structured audit events (optional [model] extra)
  • DRF integration — auto-detects drf_action, drf_view_class, serializer, auth/permission classes (optional [drf] extra)
  • Request body capture — opt-in JSON body capture with scrubbing and size limits
  • OTel JSONL output — every event is a single JSON line following the OTel LogRecord envelope, ready for Loki/Grafana
  • Pluggable pipeline — custom filters and enrichers run before emission

Dependencies

Package Role
django-sec-audit (this) Django integration
sec-audit Core (events, context, IP resolution, scrubbing)
sec-audit-logging Logging runtime, formatters, SIEM handlers

Quick Start

# settings.py

INSTALLED_APPS = [
    'sec_audit.django.apps.SecAuditConfig',   # early, before your apps
    # ...
]

MIDDLEWARE = [
    # ... Django security middleware
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'sec_audit.django.middleware.AuditMiddleware',  # last or near-last
]

SEC_AUDIT = {
    'core': {
        'source': 'myapp',               # appears as resource.service.name
        'log_request_bodies': False,      # opt-in
        'log_ok_responses': False,        # only 4xx/5xx by default
    },
    'logging': {
        'schema_version': '1.0',
    },
    'django': {
        'include_usernames': False,       # opt-in for GDPR considerations
    },
}

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        # Injects the resolved SEC_AUDIT config at construction.
        'audit_jsonl': {
            '()': 'sec_audit.django.logging.formatters.audit_jsonl_formatter',
        },
    },
    'handlers': {
        'audit_stdout': {
            'class': 'logging.StreamHandler',
            'formatter': 'audit_jsonl',
        },
    },
    'loggers': {
        'sec_audit.audit': {
            'handlers': ['audit_stdout'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}

Stdout is the supported delivery path (stdout JSONL -> Grafana Alloy -> Loki). For local file output, swap the handler for a stdlib logging.handlers.RotatingFileHandler using the same audit_jsonl formatter.

Usage Guide

For a step-by-step setup and configuration walkthrough, see docs/how-to-use.md.

Monitoring with Loki/Grafana

Audit events are OTel JSONL, ready to ship to Loki (sec_audit.audit JSONL → Grafana Alloy → Loki → Grafana). The bundled sec-audit-loki-init command generates the whole local stack — see docs/loki-setup.md.

Configuration

All settings live under the SEC_AUDIT dict in settings.py. Three sections are recognised:

core (CoreAuditConfig)

Setting Default Description
source 'sec-audit' Service name in resource.service.name
ignore_paths () Regex patterns; matching paths are skipped
ignore_status_codes frozenset() Status code values to skip (e.g. {301, 302})
sample_rate 1.0 Sampling rate for successful (2xx) responses
log_ok_responses False Enable logging for 2xx responses
log_request_bodies False Enable request body capture
log_body_paths () Regex patterns; only matching paths capture bodies
body_methods {'POST', 'PUT', 'PATCH'} HTTP methods eligible for body capture
max_body_bytes 4096 Maximum JSON body size in bytes
sensitive_keys DEFAULT_SENSITIVE_KEYS Built-in key patterns to scrub (incl. password, secret, token, apikey, etc.)
sensitive_key_allowlist () Exact (compacted) field names never redacted, even when a sensitive_keys substring matches — e.g. credit_card_last4, token_expiry
sensitive_value_patterns () Regex patterns matching sensitive values to scrub

logging (LoggingAuditConfig)

Setting Default Description
schema_version '1.0' Schema version string in every event
projection_limits ProjectionLimits() Bounds for dict/list nesting and string sizes (accepts a dict or ProjectionLimits)

File-rotation parameters (maxBytes/backupCount/filename) are configured on the handler in Django's LOGGING dict, not here.

django (DjangoAuditConfig)

Setting Default Description
include_usernames False Include user.name in events (opt-in for GDPR)
trusted_proxy_cidrs () CIDR ranges considered trusted proxies
trusted_proxy_count None Number of trusted proxies (leftmost N IPs are strip)
emit_session_id False Emit correlated session.id in events (opt-in; writes to request.session)
filters () Dotted paths to filter callable/classes
enrichers () Dotted paths to enricher callable/classes

Event Types

auth.login.success        auth.login.failed
auth.logout.success       auth.logout.unknown
http.response.success     http.response.client_error   http.response.server_error
model.create              model.update                 model.delete         model.access

Output Format

Each event is a single JSON line:

{
  "timestamp": 1712345678000000000,
  "observed_timestamp": 1712345678000000000,
  "severity_text": "WARNING",
  "severity_number": 13,
  "body": "http.response",
  "resource": { "service.name": "sec-audit" },
  "instrumentation_scope": { "name": "sec_audit.django.middleware", "version": "1.0.0" },
  "attributes": {
    "event_type": "http.response.client_error",
    "source.address": "203.0.113.10",
    "http.request.method": "POST",
    "http.response.status_code": 404,
    "url.full": "https://example.test/api/transfer",
    "url.path": "/api/transfer",
    "user.id": "42"
  },
  "event_name": "http.response.client_error"
}

Optional Extras

Extra Dependencies
pip install django-sec-audit[model] django-auditlog
pip install django-sec-audit[drf] djangorestframework
pip install django-sec-audit[full] Both

Development

pip install -e "packages/django-sec-audit[dev]"
pytest
ruff check .

License

MIT

Metadata

Release files for django-sec-audit 0.1.0a5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-sec-audit 0.1.0a5
File Size Uploaded Provenance Actions
django_sec_audit-0.1.0a5.tar.gz 42.1 kB Without provenance Details for django_sec_audit-0.1.0a5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-sec-audit 0.1.0a5
File Interpreter ABI Platform Actions
django_sec_audit-0.1.0a5-py3-none-any.whl Python 3 none any Details for django_sec_audit-0.1.0a5-py3-none-any.whl

Total release size: 71.4 kB

Release files / django_sec_audit-0.1.0a5.tar.gz

Download URL django_sec_audit-0.1.0a5.tar.gz
Size 42.1 kB
Tags Source
SHA-256 checksum
How to use checksums
abe2e47b3c89e26136f9f4fe50736d9f4a7bc6a5dca32c2470d011f90afa3dd2
BLAKE2b-256 checksum
How to use checksums
84f36905b843d9d6682cb7f88252b973c3a1efcd05430e9dfeebd7d3f4980bc0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.2

Release files / django_sec_audit-0.1.0a5-py3-none-any.whl

Download URL django_sec_audit-0.1.0a5-py3-none-any.whl
Size 29.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a2ace296c77dd81c7f2bfdbc5a527118725157282b10cf433944ee849db8c61e
BLAKE2b-256 checksum
How to use checksums
b944f8494a07f74721ed083edaca74c11a90d91f595d79308f8e8b8e9c322c1b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.2

Security for django-sec-audit 0.1.0a5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page