Reputation: 1760
I want to log every request sent to Django.
There are some posts online about logging middleware. The Django documentation talks about logger configuration and it seems that I can set it up to log everything without writing middleware.
INFO
level messages, with DEBUG = False
and no middleware?Upvotes: 5
Views: 5524
Reputation: 601
For anyone looking for sample of logging middle ware create a folder in your project name middleware and create init.py under that folder and create a file name logging.py and copy this sample code.
import logging
import time
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
formatter = logging.Formatter(fmt="%(asctime)s %(levelname)s; %(message)s")
handler.formatter = formatter
logger.addHandler(handler)
logger.setLevel(logging.INFO)
class LoggingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
start_time = time.time()
request_data = {
"method": request.method,
'ip_address': request.META.get('REMOTE_ADDR'),
'path': request.path
}
logger.info(request_data)
response = self.get_response(request)
duration = time.time() - start_time
response_dict = {
"status_code": response.status_code,
"duration": round(duration, 2)
}
logger.info(response_dict)
return response
then in your settings.py import the middleware that you created for example
MIDDLEWARE = [
'yourapp.middleware.logging.LoggingMiddleware',
]
Source: link
Note: I am using Django 5 for more information about Django middle ware https://docs.djangoproject.com/en/5.1/topics/http/middleware/
Upvotes: 0
Reputation: 3649
if want to log every request, in that case, you should use Logging in middleware https://djangosnippets.org/snippets/428/
Upvotes: 3