Some checks failed
Build And Test / build-and-push (push) Failing after 33s
- Add gunicorn access/error log options to Dockerfile - Create RequestLoggingMiddleware for detailed request logging - Log request method, path, host, IP, NHN headers, response status, duration Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
54 lines
1.5 KiB
Python
54 lines
1.5 KiB
Python
# nhn_prj/middleware.py
|
|
import logging
|
|
import time
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class RequestLoggingMiddleware:
|
|
"""모든 요청을 로깅하는 미들웨어"""
|
|
|
|
def __init__(self, get_response):
|
|
self.get_response = get_response
|
|
|
|
def __call__(self, request):
|
|
# 요청 시작 시간
|
|
start_time = time.time()
|
|
|
|
# 요청 정보 로깅
|
|
logger.info(
|
|
f"[REQUEST] {request.method} {request.path} "
|
|
f"| Host: {request.get_host()} "
|
|
f"| IP: {self.get_client_ip(request)}"
|
|
)
|
|
|
|
# 헤더 로깅 (디버깅용)
|
|
nhn_headers = {
|
|
k: v for k, v in request.headers.items()
|
|
if k.lower().startswith('x-nhn')
|
|
}
|
|
if nhn_headers:
|
|
logger.info(f"[HEADERS] NHN Headers: {nhn_headers}")
|
|
|
|
# 응답 처리
|
|
response = self.get_response(request)
|
|
|
|
# 응답 시간 계산
|
|
duration = time.time() - start_time
|
|
|
|
# 응답 정보 로깅
|
|
logger.info(
|
|
f"[RESPONSE] {request.method} {request.path} "
|
|
f"| Status: {response.status_code} "
|
|
f"| Duration: {duration:.3f}s"
|
|
)
|
|
|
|
return response
|
|
|
|
def get_client_ip(self, request):
|
|
"""클라이언트 IP 추출"""
|
|
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
|
|
if x_forwarded_for:
|
|
return x_forwarded_for.split(',')[0].strip()
|
|
return request.META.get('REMOTE_ADDR', 'unknown')
|