63 lines
2.0 KiB
Python
63 lines
2.0 KiB
Python
import hashlib
|
|
import traceback
|
|
import threading
|
|
from django.core.signals import got_request_exception
|
|
from django.dispatch import receiver
|
|
|
|
|
|
@receiver(got_request_exception)
|
|
def log_request_exception(sender, request, **kwargs):
|
|
def _save():
|
|
try:
|
|
import sys
|
|
from .models import ErrorLog
|
|
|
|
exc_info = sys.exc_info()
|
|
if not exc_info[0]:
|
|
return
|
|
|
|
exception_type = exc_info[0].__name__
|
|
tb_string = ''.join(traceback.format_exception(*exc_info))
|
|
message = str(exc_info[1]) if exc_info[1] else ''
|
|
|
|
hash_input = f"{exception_type}:{request.path}:{message[:100]}"
|
|
hash_key = hashlib.md5(hash_input.encode()).hexdigest()
|
|
|
|
user = None
|
|
try:
|
|
if hasattr(request, 'user') and request.user.is_authenticated:
|
|
user = request.user
|
|
except Exception:
|
|
pass
|
|
|
|
ip_address = None
|
|
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
|
|
if x_forwarded_for:
|
|
ip_address = x_forwarded_for.split(',')[0].strip()
|
|
else:
|
|
ip_address = request.META.get('REMOTE_ADDR')
|
|
|
|
existing = ErrorLog.objects.filter(hash_key=hash_key).first()
|
|
if existing:
|
|
existing.occurrence_count += 1
|
|
existing.save(update_fields=['occurrence_count', 'timestamp'])
|
|
else:
|
|
ErrorLog.objects.create(
|
|
level='ERROR',
|
|
message=message[:1000],
|
|
module='request',
|
|
function='process_request',
|
|
exception_type=exception_type,
|
|
traceback=tb_string,
|
|
user=user,
|
|
ip_address=ip_address,
|
|
path=request.path[:255],
|
|
hash_key=hash_key,
|
|
)
|
|
except Exception:
|
|
pass
|
|
|
|
thread = threading.Thread(target=_save)
|
|
thread.daemon = True
|
|
thread.start()
|