add logger in setting & request formatter

This commit is contained in:
2025-10-27 12:42:49 +03:30
parent 15c2ecfebb
commit 09f375b98d
3 changed files with 82 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
import logging
from django.http import HttpRequest
class RequestFormatter(logging.Formatter):
def format(self, record):
request = getattr(record, 'request', None)
if isinstance(request, HttpRequest):
# مرحله ۱: از X-Forwarded-For (در صورت وجود)
ip = request.META.get('HTTP_X_FORWARDED_FOR')
# مرحله ۲: از REMOTE_ADDR
if not ip:
ip = request.META.get('REMOTE_ADDR')
# مرحله ۳: اگر هنوز چیزی نیست، مقدار پیش‌فرض بده (مثلاً localhost)
if not ip:
ip = '127.0.0.1'
# تمیزکاری برای لیست آی‌پی‌ها
if ',' in ip:
ip = ip.split(',')[0].strip()
record.client_ip = ip
record.path = request.path
else:
record.client_ip = '-'
record.path = '-'
return super().format(record)