|
17 | 17 | caching system to set a key and then triggering the actual event from middleware |
18 | 18 | """ |
19 | 19 |
|
| 20 | +import json |
20 | 21 | import logging |
| 22 | +import uuid |
21 | 23 | from http import HTTPStatus |
22 | 24 | from threading import local |
23 | 25 |
|
@@ -53,8 +55,46 @@ def __call__(self, request): |
53 | 55 | if request.user.is_authenticated: |
54 | 56 | _user.value = request.user |
55 | 57 |
|
| 58 | + # Log all requests to our v2 API endpoints |
| 59 | + if settings.ENABLE_API_LOGGING and request.path.startswith("/rest/v2/"): |
| 60 | + try: |
| 61 | + # Generate a trace ID for each request |
| 62 | + trace_id = str(uuid.uuid4()) |
| 63 | + request.trace_id = trace_id |
| 64 | + # Log the IP address of the request |
| 65 | + ip_address = request.META.get("REMOTE_ADDR") |
| 66 | + logger.info(f"[Trace ID: {trace_id}] IP Address: {ip_address}") |
| 67 | + # Log the user if authenticated |
| 68 | + if request.user.is_authenticated: |
| 69 | + logger.info(f"[Trace ID: {trace_id}] User: {request.user.username}") |
| 70 | + # Log the request details |
| 71 | + logger.info( |
| 72 | + f"[Trace ID: {request.trace_id}] Request: {request.method} {request.get_full_path()} - body size: {len(request.body) if request.body else 0} bytes" |
| 73 | + ) |
| 74 | + if request.body and request.headers["Content-Type"] == "application/json": |
| 75 | + # Only log first 512 characters of the request body to avoid flooding the logs |
| 76 | + logger.info( |
| 77 | + f"[Trace ID: {request.trace_id}] Request body: {json.dumps(json.loads(request.body))[:512]}" |
| 78 | + ) |
| 79 | + except Exception as e: |
| 80 | + logger.exception( |
| 81 | + f"[Trace ID: {request.trace_id}] An error occurred when parsing request: {str(e)}" |
| 82 | + ) |
| 83 | + |
56 | 84 | response = self.get_response(request) |
57 | 85 |
|
| 86 | + # Log all responses to our v2 API endpoints |
| 87 | + if settings.ENABLE_API_LOGGING and request.path.startswith("/rest/v2/"): |
| 88 | + try: |
| 89 | + # Log the response details |
| 90 | + logger.info( |
| 91 | + f"[Trace ID: {request.trace_id}] Response status: {response.status_code} - content size: {len(response.content)} bytes" |
| 92 | + ) |
| 93 | + except Exception as e: |
| 94 | + logger.exception( |
| 95 | + f"[Trace ID: {request.trace_id}] An error occurred when logging response: {str(e)}" |
| 96 | + ) |
| 97 | + |
58 | 98 | triggers = { |
59 | 99 | "Config": trigger_write_config.send, |
60 | 100 | "Rules": trigger_write_rules.send, |
|
0 commit comments