Skip to content

Commit

Permalink
Merge pull request #7 from MEHRSHAD-MIRSHEKARY/feature/request-middle…
Browse files Browse the repository at this point in the history
…ware

Feature/request middleware
  • Loading branch information
ARYAN-NIKNEZHAD authored Aug 17, 2024
2 parents 159169a + d4b4d04 commit 14d2206
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
1 change: 1 addition & 0 deletions django_logging/middleware/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .request_middleware import RequestLogMiddleware
84 changes: 84 additions & 0 deletions django_logging/middleware/request_middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import logging
from django.contrib.auth import get_user_model
from django.http import HttpResponse, HttpRequest
from typing import Callable

logger = logging.getLogger(__name__)


class RequestLogMiddleware:
"""
Middleware to log information about each incoming request.
This middleware logs the request path, the user making the request (if authenticated),
and the user's IP address.
"""

def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
"""
Initializes the RequestLogMiddleware instance.
Args:
get_response: A callable that returns an HttpResponse object.
"""
self.get_response = get_response
user_model = get_user_model()
self.username_field = user_model.USERNAME_FIELD

def __call__(self, request: HttpRequest) -> HttpResponse:
"""
Processes an incoming request and logs relevant information.
Args:
request: The incoming request object.
Returns:
The response object returned by the view function.
"""
# Before view (and later middleware) are called.
response = self.get_response(request)

# After view is called.
if hasattr(request, "user") and request.user.is_authenticated:
user = getattr(request.user, self.username_field, "Anonymous")
else:
user = "Anonymous"

# Get the user's IP address
ip_address = self.get_ip_address(request)

# Get the user agent
user_agent = self.get_user_agent(request)

# Attach IP and user agent to the request
request.ip_address = ip_address
request.browser_type = user_agent

logger.info(
f"Request Info: (request_path: {request.path}, user: {user},"
f"\nIP: {ip_address}, user_agent: {user_agent})"
)

return response

@staticmethod
def get_ip_address(request: HttpRequest) -> str:
"""
Retrieves the client's IP address from the request object.
"""
ip_address = request.META.get("HTTP_X_FORWARDED_FOR")
if ip_address:
ip_address = ip_address.split(",")[0]
else:
ip_address = request.META.get("LIMITED_ACCESS")
if not ip_address:
ip_address = request.META.get("REMOTE_ADDR")

return ip_address

@staticmethod
def get_user_agent(request: HttpRequest) -> str:
"""
Retrieves the client's user agent from the request object.
"""
return request.META.get("HTTP_USER_AGENT", "Unknown User Agent")

0 comments on commit 14d2206

Please sign in to comment.