Skip to main content

Framework-agnostic HTTP logger with payload masking

Project description

🕵️‍♂️ BlackBox Logger

PyPI License

A universal request/response logger for Django, Flask, FastAPI, and other Python apps.
Automatically logs requests and responses, user info, IP address, and more — with masked sensitive data — into a log file and SQLite/PostgreSQL database.


🚀 Features

  • ✅ Logs all HTTP requests and responses
  • ✅ Logs to both blackbox.log file and SQLite or PostgreSQL DB
  • ✅ Automatically masks sensitive fields (e.g., password, token, etc.)
  • ✅ Logs user (if available), IP address, user agent, and request duration
  • ✅ Skips HTML/JS or large responses automatically
  • ✅ Supports log rotation
  • ✅ Decorator-based and middleware-based integration
  • ✅ Works out-of-the-box in Django, Flask, and FastAPI

📦 Installation

pip install blackbox-logger
# Or install directly from GitHub:
pip install git+https://github.com/avi9r/blackbox_logger.git

📁 Logs

  • log/blackbox.log — rotating file logs
  • log/blackbox_logs.db — SQLite DB (or PostgreSQL if configured)

⚙️ Usage

🟩 Django Middleware

from django.utils.deprecation import MiddlewareMixin
from blackbox_logger.logger import HTTPLogger
import time

logger = HTTPLogger()

class BlackBoxLoggerMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request._start_time = time.time()
        logger.log_request(request.method, request.path, dict(request.headers), request.body, request)

    def process_response(self, request, response):
        duration = time.time() - getattr(request, "_start_time", time.time())
        logger.log_response(
            request.method, request.path, dict(response.headers),
            response.content, response.status_code, request, duration
        )
        return response

Then in settings.py:

MIDDLEWARE = [
    'your_project.middleware.BlackBoxLoggerMiddleware',
    ...
]

🔵 Django Decorator Usage

from blackbox_logger.logger import HTTPLogger
logger = HTTPLogger()

@logger.decorator
def my_view(request):
    return JsonResponse({"message": "OK"})

🟖 Flask Middleware

from flask import Flask, request
from flask_login import current_user
from blackbox_logger.logger import HTTPLogger
import time

logger = HTTPLogger(get_user=lambda h, r=None: current_user.username if current_user.is_authenticated else "Anonymous")
app = Flask(__name__)

@app.before_request
def log_request():
    request._start_time = time.time()
    logger.log_request(request.method, request.path, dict(request.headers), request.get_data(), request)

@app.after_request
def log_response(response):
    duration = time.time() - getattr(request, '_start_time', time.time())
    logger.log_response(
        request.method, request.path, dict(response.headers),
        response.get_data(), response.status_code, request, duration
    )
    return response

🟨 Flask Decorator Usage

@logger.decorator
def your_flask_view():
    return jsonify({"msg": "Hello"})

🟘 FastAPI Middleware

from fastapi import FastAPI, Request, Response
from blackbox_logger.logger import HTTPLogger

logger = HTTPLogger()
app = FastAPI()

@app.middleware("http")
async def blackbox_logger_middleware(request: Request, call_next):
    request.state.user = "Anonymous"  # attach user if needed
    body = await request.body()
    logger.log_request(request.method, str(request.url), dict(request.headers), body, request)

    response = await call_next(request)
    response_body = b"".join([chunk async for chunk in response.body_iterator])
    response.body_iterator = iter([response_body])

    logger.log_response(
        request.method, str(request.url), dict(response.headers),
        response_body, response.status_code, request
    )
    return response

🟦 FastAPI Decorator Usage

@app.get("/hello")
@logger.decorator
def hello(request: Request):
    return {"hello": "world"}

🔍 Decorator vs Middleware Summary

Integration Style Need Decorator? Works Without It?
Django/Flask/FastAPI Middleware ❌ No ✅ Yes
Manual log_request/log_response ❌ No ✅ Yes
Only with @decorator ✅ Yes (if no middleware) ✅ Yes

🔐 Masking Sensitive Data

Default masked fields:

["password", "token", "access_token", "secret", "authorization", "csrfmiddlewaretoken"]

To add custom fields:

logger = HTTPLogger(custom_mask_fields={"otp", "session_id"})

📃 PostgreSQL Support

Set these environment variables:

BLACKBOX_DB_TYPE=postgres
BLACKBOX_PG_DB=blackbox_logs
BLACKBOX_PG_USER=postgres
BLACKBOX_PG_PASSWORD=secret
BLACKBOX_PG_HOST=localhost
BLACKBOX_PG_PORT=5432

🔄 Log Rotation

Enable rotating file logs:

BLACKBOX_LOG_MAX_SIZE=1048576     # 1MB
BLACKBOX_LOG_BACKUP_COUNT=5       # Keep 5 backups

📜 Sample Output

2025-06-19 18:29:15 [INFO] [REQUEST] POST /api/login | User: admin | IP: 127.0.0.1 | Payload: {"username": "admin", "password": "***"}
2025-06-19 18:29:15 [INFO] [RESPONSE] POST /api/login | User: admin | IP: 127.0.0.1 | Status: 200 | Duration: 0.23s | Response: {"status": "ok"}

📓 License

MIT License

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

blackbox_logger-0.2.3.tar.gz (8.9 kB view details)

Uploaded Source

Built Distribution

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

blackbox_logger-0.2.3-py3-none-any.whl (8.2 kB view details)

Uploaded Python 3

File details

Details for the file blackbox_logger-0.2.3.tar.gz.

File metadata

  • Download URL: blackbox_logger-0.2.3.tar.gz
  • Upload date:
  • Size: 8.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.5

File hashes

Hashes for blackbox_logger-0.2.3.tar.gz
Algorithm Hash digest
SHA256 9657c187691f63c03714f8ce58b6df6f8ea4cc64e5674e0c1ed07b60b4fdd169
MD5 f3d42336e04082b80f6f63f74a3999ca
BLAKE2b-256 a4072c7d194c356db1de2a1ed967d78c6d23c9460b6101c0644cb5047b0a8da9

See more details on using hashes here.

File details

Details for the file blackbox_logger-0.2.3-py3-none-any.whl.

File metadata

File hashes

Hashes for blackbox_logger-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 97b5d019e480a704e2f82ae8491a7d4ec9cfa57d1f5f2eea21ab50747cd3dcb5
MD5 41979b7a733da7d34329a5ba5ed02f16
BLAKE2b-256 ba24879b72c3f493d8a4820d6a550d99bc76abff522b90838b58c245234e4572

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