Skip to main content

Automatic exception logging for Django applications.

Project description

Django Rest Exception Logger

This package provides middleware for automatically logging exceptions in Django applications. It captures and stores exception details such as the error message, stack trace, request data, headers, and the view where the error occurred.

Features

  • Automatically logs exceptions in the database
  • Captures request payloads and headers for debugging
  • Customizable via model relationships with your user model
  • Handles specific exceptions like PermissionDenied and ParseError with customized responses

Requirements

  • Python 3.8+
  • Django 3.2+
  • Django Rest Framework 3.12+

Installation

  1. Install the package

    You can install this package from PyPI using pip:

    pip install django-rest-exception-logger
    
  2. Add the middleware

    To enable automatic exception logging, add ExceptionMiddleware to your MIDDLEWARE list in your Django project's settings.py file:

    MIDDLEWARE = [
        # Other middlewares...
        'django_rest_exception_logger.middleware.ExceptionMiddleware',
    ]
    
  3. Add the ExceptionLog model

    This package comes with the ExceptionLog model, which stores information about exceptions. You need to integrate it into your project.

    • Add exception_logging to the INSTALLED_APPS list in settings.py:

      INSTALLED_APPS = [
          # Other apps...
          'django_rest_exception_logger',
      ]
      
    • Run migrations to create the necessary database tables:

      python manage.py migrate
      
    • if migration not detected, run this command

       python manage.py makemigrations django_rest_exception_logger
      
  4. Configure the user model (optional)

    By default, the ExceptionLog model has a foreign key to the auth.User model. If you are using a custom user model, ensure that the ExceptionLog model's user field is compatible with your custom user model.

  5. Customize Middleware behavior (optional)

    You can extend the ExceptionMiddleware or modify it to add additional custom exception handling as needed for your application.

Usage

Once the middleware is installed, it will automatically log exceptions that occur in your views to the ExceptionLog model. The logged information will include:

  • Exception type and message
  • Full traceback
  • Request payload (for POST, PUT, PATCH requests)
  • Request headers and parameters
  • View name where the exception occurred
  • User who initiated the request (if available)

Manual logging (optional)

If you need to log exceptions from other places (views, Celery tasks, management commands, signals), you can use log_exception.

from django_rest_exception_logger.utils import log_exception

try:
    # ... your code ...
    raise ValueError("Invalid input")
except Exception as exc:
    log_exception(
        exc,
        request=request,  # optional
        message="Payment failed",  # optional override for ExceptionLog.message
        extra={"order_id": 123, "step": "charge"},  # optional extra context
        log_type="error",  # optional (default: "error")
        view_name="payments.charge",  # optional override
    )

extra is stored under "_extra" inside request_payload.

Usage Examples

# 1. Query All Error Logs
from django_rest_exception_logger.models import ExceptionLog

# Retrieve all error logs ordered by most recent
error_logs = ExceptionLog.objects.filter(log_type="error").order_by('-timestamp')

for log in error_logs:
    print(log.message, log.timestamp)

# 2. Create a New Info Log
from django_rest_exception_logger.models import ExceptionLog

# Create a new info log entry
ExceptionLog.objects.create(
    log_type="info",
    message="This is an informational log",
    view_name="my_view"
)

Example Use Cases

  • Debugging Production Issues: Track unexpected errors in production environments with full context, including which user triggered the error and what data they sent.
  • Security Auditing: Capture unauthorized access attempts and permission errors for analysis and potential remediation.
  • Improving User Experience: With detailed logs, identify common errors and enhance your application's stability and error handling.

Testing

Run the test suite:

pip install -r requirements-dev.txt  # if you use a dev requirements file
pytest

To manually verify middleware behavior, you can raise an exception in a view and check the logs in your admin or database:

def test_view(request):
    raise Exception("Test exception for logging")

After visiting this view, a new entry should appear in the ExceptionLog model, capturing the details of the error.

Contributing

Feel free to open an issue or submit a pull request if you have suggestions for improvements.

License

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

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

django_rest_exception_logger-0.3.0.tar.gz (13.1 kB view details)

Uploaded Source

Built Distribution

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

django_rest_exception_logger-0.3.0-py3-none-any.whl (14.8 kB view details)

Uploaded Python 3

File details

Details for the file django_rest_exception_logger-0.3.0.tar.gz.

File metadata

File hashes

Hashes for django_rest_exception_logger-0.3.0.tar.gz
Algorithm Hash digest
SHA256 5c5632cdf43e84c6fd58de70e97cc566bf4dc8513bf51a21b6179189f5c2818d
MD5 0b5af71ef238a873f78682d1ec78b11a
BLAKE2b-256 188e759e82c3728d93400443f3eebe6e29a038ce2f6414aac688899b2054b9ba

See more details on using hashes here.

File details

Details for the file django_rest_exception_logger-0.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_rest_exception_logger-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 313a04a23b99807aefb4b86552db9d7cc36d7b2f8864a4f35f05a224a51b180f
MD5 b9c89964c0242396dc183bd706baed68
BLAKE2b-256 1e92509cc4ce96f61623c5244a349b02c08b4dc7ac2349bf2e7d53ea9954f15d

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