Skip to content

Haroonhsa007/django-centralized-debug-and-logging-panel

Repository files navigation

Tests codecov PyPI version Python versions License: MIT

Django centralized Debug and Logging Panel

A Django Admin panel for centrallized error logging, line wise debugging execption logging in production and in dev env

Compatible with dj-control-room. Register this panel in the Control Room to manage it from a centralized dashboard.

Docs

https://haroonhsa007.github.io/django-centralized-debug-and-logging-panel/

Features

  • Centralized log storage: Persist structured log and exception events (level, message, traceback, request, user, environment, and more) in your Django database.
  • Admin panel UI: Browse, search, and filter recent log events directly inside Django admin, with deep links into individual events.
  • Safe dev-only printing: Use a cprint helper that only prints when DEBUG=True, keeping noisy prints out of production.

Project Structure

django-centralized-debug-and-logging-panel/
├── django_centralized_debug_and_logging_panel/         # Main package
│   ├── templates/           # Django templates
│   ├── views.py             # Django views
│   └── urls.py              # URL patterns
├── example_project/         # Example Django project
├── tests/                   # Test suite
├── images/                  # Screenshots for README
└── requirements.txt         # Development dependencies

Requirements

  • Python 3.9+
  • Django 4.2+

Screenshots

Django Admin Integration

Seamlessly integrated into your Django admin interface. A new section for django-centralized-debug-and-logging-panel will appear in the same places where your models appear, and a dedicated panel view provides a paginated, filterable list of recent log events.

Admin Home

Installation

1. Install the Package

pip install django-centralized-debug-and-logging-panel

2. Add to Django Settings

Add django_centralized_debug_and_logging_panel to your INSTALLED_APPS:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_centralized_debug_and_logging_panel',  # Add this line
    # ... your other apps
]

3. Configure Settings (Optional)

Add any custom configuration to your Django settings if needed using the CENTRAL_PANEL namespace:

CENTRAL_PANEL = {
    "RETENTION_DAYS": 30,  # How long to keep log events
    "REDACT_HEADERS": ["authorization", "cookie"],
    "MAX_BODY_LENGTH": 4096,
    "MAX_STACKTRACE_LENGTH": 20000,
    # Optional: dotted path to a callable that can enrich the payload
    # before it is saved as a LogEvent instance.
    # "ENRICH_EVENT_CALLBACK": "path.to.your.callable",
}

4. Include URLs

Add the Panel URLs to your main urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/django-centralized-debug-and-logging-panel/', include('django_centralized_debug_and_logging_panel.urls')),  # Add this line
    path('admin/', admin.site.urls),
]

5. Run Migrations and Create Superuser

python manage.py migrate
python manage.py createsuperuser  # If you don't have an admin user

6. Access the Panel

  1. Start your Django development server:

    python manage.py runserver
  2. Navigate to the Django admin at http://127.0.0.1:8000/admin/

  3. Look for the "DJANGO CENTRALIZED DEBUG AND LOGGING PANEL" section in the admin interface

  4. Use the Log events model or the dedicated panel URL (/admin/django-centralized-debug-and-logging-panel/) to browse recent log entries.

Usage

Dev-only cprint

Instead of using plain print() in your views or tasks, use cprint so that debug output only appears when DEBUG=True:

from django_centralized_debug_and_logging_panel.utils import cprint

def my_view(request):
    cprint("Got request for", request.path)
    # Optional: change log level and color
    cprint("Something suspicious", level="WARNING", color="yellow")

In production (DEBUG=False), cprint is a no-op and will not clutter your logs or stdout.

Capturing logs and exceptions in LogEvent

The package provides a logging handler CentralPanelHandler that writes structured log records into the LogEvent model. A typical configuration looks like this:

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {
        "central_panel": {
            "level": "INFO",
            "class": "django_centralized_debug_and_logging_panel.logging_handlers.CentralPanelHandler",
        },
        "console": {
            "class": "logging.StreamHandler",
        },
    },
    "loggers": {
        # Your project code
        "myproject": {
            "handlers": ["central_panel", "console"],
            "level": "INFO",
            "propagate": True,
        },
        # Django HTTP exceptions
        "django.request": {
            "handlers": ["central_panel", "console"],
            "level": "ERROR",
            "propagate": False,
        },
    },
}

Once configured, any logging calls made through these loggers will create LogEvent rows that you can browse in the panel.

Request context middleware

To enrich log entries with request and user information, add the provided middleware near the top of your MIDDLEWARE list:

MIDDLEWARE = [
    "django_centralized_debug_and_logging_panel.middleware.RequestContextMiddleware",
    # ... the rest of your middleware ...
]

This middleware stores the current request in thread-local storage so the logging handler can attach path, method, headers, IP address, user, and other context to each LogEvent.

Enrichment callback

If you need to attach custom metadata to every log event, you can use the ENRICH_EVENT_CALLBACK setting:

# settings.py

def add_custom_tag(payload: dict) -> None:
    extra = payload.get("extra") or {}
    extra["service"] = "payments"
    payload["extra"] = extra


CENTRAL_PANEL = {
    "ENRICH_EVENT_CALLBACK": "myproject.settings.add_custom_tag",
}

The callback receives the payload dict just before it is saved as a LogEvent instance and can mutate it in place.

Pruning old log events

To clean up old data, run the management command:

python manage.py central_panel_prune_logs

By default it uses CENTRAL_PANEL["RETENTION_DAYS"] (30 days if not overridden) to delete events older than the configured age.

DJ Control Room Integration

This panel is designed to work seamlessly with DJ Control Room, a centralized dashboard for managing Django admin panels.

Integration

register your panel in django's installed apps

  1. Add dj_control_room to INSTALLED_APPS:

    INSTALLED_APPS = [
        # ... other apps
        'dj_control_room',
        'django_centralized_debug_and_logging_panel',
    ]
  2. Include the Control Room URLs in your urls.py:

    urlpatterns = [
        path('', include('django_centralized_debug_and_logging_panel.urls')),  # Panel URLs
        path('admin/dj-control-room/', include('dj_control_room.urls')),  # Control Room
        path('admin/', admin.site.urls),
    ]
  3. Visit /admin/dj-control-room/ to see all your panels in one place!

Panel Configuration

The panel is configured via the panel.py file with the following attributes:

  • ID: django_centralized_debug_and_logging_panel
  • Name: Django centralized Debug and Logging Panel
  • Description: A Django Admin panel for centrallized error logging, line wise debugging execption logging in production and in dev env
  • Icon: layers

You can customize these values by editing django_centralized_debug_and_logging_panel/panel.py.

License

This project is licensed under the MIT License. See the LICENSE file for details.


Development Setup

If you want to contribute to this project or set it up for local development:

Prerequisites

  • Python 3.9 or higher
  • Redis server running locally
  • Git
  • Autoconf
  • Docker

It is reccommended that you use docker since it will automate much of dev env setup

1. Clone the Repository

git clone https://github.com/haroonhsa007/django-centralized-debug-and-logging-panel.git
cd django-centralized-debug-and-logging-panel

2a. Set up dev environment using virtualenv

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

pip install -e . # install django-centralized-debug-and-logging-panel package locally
pip intall -r requirements.txt  # install all dev requirements

# Alternatively
make install # this will also do the above in one single command

2b. Set up dev environment using docker

make docker_up  # bring up all services (redis, memached) and dev environment container
make docker_shell  # open up a shell in the docker conatiner

3. Set Up Example Project

The repository includes an example Django project for development and testing

cd example_project
python manage.py migrate
python manage.py createsuperuser

4. Populate Test Data (Optional)

Add any custom management commands for populating test data if needed.

6. Run the Development Server

python manage.py runserver

Visit http://127.0.0.1:8000/admin/ to access the Django admin with Django centralized Debug and Logging Panel. Use the django-centralized-debug-and-logging-panel section or the dedicated panel URL to explore captured log events.

7. Running Tests

The project includes a comprehensive test suite. You can run them by using make or by invoking pytest directly:

# build and install all dev dependencies and run all tests inside of docker container
make test_docker

# Test without the docker on your host machine.
# note that testing always requires a redis and memcached service to be up.
# these are mostly easily brought up using docker
make test_local

8. Using with Whitenoise

The panel's static assets live under django_centralized_debug_and_logging_panel/static/ and are compatible with Django's ManifestStaticFilesStorage and Whitenoise. Follow the Whitenoise documentation to enable it in your project; once configured, running collectstatic will pick up the panel's assets automatically.

If you use the Unfold admin theme, the panel works with the standard admin integration; you can further customize the templates under django_centralized_debug_and_logging_panel/templates/ to better match your Unfold styling if desired.

About

No description, website, or topics provided.

Resources

License

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors