Исправление двойного логирования ошибок

This commit is contained in:
2026-07-19 19:45:03 +03:00
parent 7c13582fdb
commit a6c9db1a71
6 changed files with 80 additions and 24 deletions

View File

@@ -8,8 +8,6 @@
Описание функции custom_exception_handler
"""
import logging
from rest_framework import status
from rest_framework.exceptions import MethodNotAllowed
from rest_framework.exceptions import NotAuthenticated
@@ -23,7 +21,6 @@ from net.xeaf.rack.models.responses import ErrorResponse
from net.xeaf.rack.utils.exceptions import ForbiddenException
from net.xeaf.rack.utils.exceptions import NotFoundException
from net.xeaf.rack.utils.exceptions import UnauthorizedException
from wsgiapp import settings
def custom_exception_handler(exc: CoreException | Exception, context: dict) -> Response:
@@ -134,17 +131,6 @@ def _make_error_response(status_code: int, detail: list | dict | str | bool | No
:return: Ответ
"""
logger = logging.getLogger(settings.LOGGER_NAME)
if status_code == status.HTTP_400_BAD_REQUEST:
logger.debug(str(exc_info), exc_info=exc_info)
elif status_code == status.HTTP_401_UNAUTHORIZED:
logger.warning(str(exc_info), exc_info=exc_info)
elif status_code == status.HTTP_403_FORBIDDEN:
logger.warning(str(exc_info), exc_info=exc_info)
elif status_code == status.HTTP_404_NOT_FOUND:
logger.error(str(exc_info), exc_info=exc_info)
else:
logger.critical(str(exc_info), exc_info=exc_info)
return ErrorResponse(status_code=status_code, detail=detail, meta=meta, pure_status=pure_status)
result = ErrorResponse(status_code=status_code, detail=detail, meta=meta, pure_status=pure_status)
result._raised_exception = exc_info
return result

View File

@@ -63,7 +63,7 @@ class CustomLoggingMiddleware:
# Обрабатываем данные запроса, ответа и перехваченного исключения
body = self._process_body(request)
exc = getattr(request, "_raised_exception", None)
exc = getattr(response, "_raised_exception", None)
status_code = response.status_code
request_id = request.META.get('HTTP_X_REQUEST_ID', '')
response_content = self._process_response(response)
@@ -172,18 +172,19 @@ class CustomLoggingMiddleware:
:param exc: Исключение
"""
if exc:
log_message += f"\nException: {str(exc)}"
if exc or status_code >= status.HTTP_400_BAD_REQUEST:
if status_code == status.HTTP_400_BAD_REQUEST:
self.logger.debug(log_message, exc_info=exc)
elif status_code in [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN]: # UNAUTHORIZED, FORBIDDEN
elif status_code == status.HTTP_401_UNAUTHORIZED:
self.logger.warning(log_message, exc_info=exc)
elif status_code == status.HTTP_403_FORBIDDEN:
self.logger.warning(log_message, exc_info=exc)
elif status_code == status.HTTP_404_NOT_FOUND:
self.logger.error(log_message, exc_info=exc)
else:
self.logger.critical(log_message, exc_info=exc)
else:
self.logger.debug(log_message)