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

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 Описание функции custom_exception_handler
""" """
import logging
from rest_framework import status from rest_framework import status
from rest_framework.exceptions import MethodNotAllowed from rest_framework.exceptions import MethodNotAllowed
from rest_framework.exceptions import NotAuthenticated 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 ForbiddenException
from net.xeaf.rack.utils.exceptions import NotFoundException from net.xeaf.rack.utils.exceptions import NotFoundException
from net.xeaf.rack.utils.exceptions import UnauthorizedException from net.xeaf.rack.utils.exceptions import UnauthorizedException
from wsgiapp import settings
def custom_exception_handler(exc: CoreException | Exception, context: dict) -> Response: 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: Ответ :return: Ответ
""" """
logger = logging.getLogger(settings.LOGGER_NAME) result = ErrorResponse(status_code=status_code, detail=detail, meta=meta, pure_status=pure_status)
result._raised_exception = exc_info
if status_code == status.HTTP_400_BAD_REQUEST: return result
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)

View File

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

View File

@@ -0,0 +1,67 @@
# DRF Rack
# Библиотека классов расширений для Django REST Framework
#
# Автор: Николай В. Анохин <n.anokhin@xeaf.net>
# Все права защищены. Лицензия: MIT
"""
Описание класса Session
"""
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
from net.xeaf.rack.core import CoreModel
from net.xeaf.rack.models.mixins import CreatedAtMixin
class JournalModel(CoreModel, CreatedAtMixin):
"""
Модель журнала работы пользователей
"""
account = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=False,
blank=False,
related_name="fk_journal_model_account",
verbose_name=_("rack.models.account"),
)
""" Аккаунт пользователя """
actual_account = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=False,
blank=False,
related_name="fk_journal_model_actual_account",
verbose_name=_("rack.models.session_model.actual_account"),
)
""" Актуальный аккаунт пользователя """
action = models.CharField(
max_length=36,
null=False,
blank=False,
verbose_name=_("rack.models.journal_model.action"),
)
""" Действие """
class Meta:
"""
Параметры конфигурации класса
"""
# Индексы для производительности
indexes = [
models.Index(fields=["account"]),
models.Index(fields=["actual_account"]),
]
# Данные таблицы
db_table = "rack_journal"
verbose_name = _("rack.models.journal")
verbose_name_plural = _("rack.models.journal_plural")

View File

@@ -38,7 +38,7 @@ class SessionModel(CoreModel, CreatedAtMixin, ExpiresAtMixin):
on_delete=models.CASCADE, on_delete=models.CASCADE,
null=False, null=False,
blank=False, blank=False,
verbose_name=_("rack.models.session_model.account"), verbose_name=_("rack.models.account"),
) )
""" Аккаунт пользователя """ """ Аккаунт пользователя """

View File

@@ -53,7 +53,7 @@ LOGGING = {
"formatters": { "formatters": {
"custom_format": { "custom_format": {
"format": "{asctime} [{levelname}] {message}", "format": "\n{asctime} [{levelname}] {message}",
"datefmt": "%Y-%m-%d %H:%M:%S", "datefmt": "%Y-%m-%d %H:%M:%S",
"style": "{", "style": "{",
}, },

View File

@@ -45,6 +45,8 @@ class VersionViewSet(ViewSetRetrieveMixin, CoreViewSet):
"version": SettingUtils.get_app_version() "version": SettingUtils.get_app_version()
} }
z = 1 / 0
return version_info return version_info
@classmethod @classmethod