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.1.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.1-py3-none-any.whl (7.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: blackbox_logger-0.2.1.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.1.tar.gz
Algorithm Hash digest
SHA256 588a038a364ca87f1a89b8e30cc6d38dfedf536b0ec1b44f75f3d09eb7e6d36a
MD5 5531acea2aeff928c85156ea187d6707
BLAKE2b-256 72690279cb5121bf82b34bbdc031e7f27783e72295c5df66829fa841fb15989d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for blackbox_logger-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d267132d0258a14f2dbbcfce5b6f00eb47d504ac042ba6d57c985585051e9a6e
MD5 ae095fedc94efba2c9d5774651e53a43
BLAKE2b-256 d2f6ad206ae947bcd982443334a60c851317b9618270df1189a0dcb5cea79699

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