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.2.tar.gz (8.4 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.2-py3-none-any.whl (7.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: blackbox_logger-0.2.2.tar.gz
  • Upload date:
  • Size: 8.4 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.2.tar.gz
Algorithm Hash digest
SHA256 a9eb85ff4b5e6c65b22ebecc38a6fbeba91e720f96bd8b200fd5cf67b36e02eb
MD5 0c3b68a02d192b4979024d88bb4629a3
BLAKE2b-256 fde25a5f636dd0343b5016f1297be95d0f4124e539b08ebaaea38ff49c64e8ac

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for blackbox_logger-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 e2aa9eb855ef41ace93f2a8475ccdea403a1ad8e10dc3567b55d95c164b9407d
MD5 67e7f85040de0af469f3041354c6aef4
BLAKE2b-256 51bb77add0be16574acce7996e71cb3b26bea152569c538ee47ebcb4ba0631e9

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