Overview
This project is designed as a learning exercise to understand how logging works in Django applications. It includes:
Simple DRF endpoints
Custom middleware that logs:
HTTP request method and path
Response status code
Request duration in milliseconds
The goal is to demonstrate how to capture, format, and view logs in a Django project.
Features
Minimal DRF API endpoint (/api/home)
Custom middleware for request/response logging
Configurable logging with Python's logging module
Structured log messages including timestamps and log levels
Setup
Clone the repository:
git clone https://github.com/kalt/django-logging-custom-middleware.git cd django-logging-custom-middleware
Create a virtual environment and activate it:
python -m venv venv source venv/bin/activate # Linux/Mac venv\Scripts\activate # Windows
Install dependencies:
pip install -r requirements.txt
Apply migrations and create a superuser:
python manage.py migrate python manage.py createsuperuser
Run the server:
python manage.py runserver
Usage
Access the API endpoint: http://127.0.0.1:8000/api/home
Use tools like curl, Postman, or a .http file to make GET/POST requests.
Observe the console for logs generated by the custom middleware.
Logging Details
Logging configuration is in settings.py
Uses Python’s standard logging module with:
Handlers (console)
Formatter for structured output (timestamp, level, logger name, message)
Middleware captures:
request.method
request.path
response.status_code
Duration in milliseconds
Example Logs Successful Request: 2026-01-07 14:32:11,842 | INFO | api.middleware | Request handled | GET /api/home | status: 200 | duration: 12.34ms
Failed Request (Method Not Allowed): 2026-01-07 14:35:22,110 | WARNING | django.request | Method Not Allowed: /api/home
Note: Middleware logs are always safe; Django internal logs may appear for 404/405 errors.
License
This project is for learning purposes. You can freely use and adapt it.