Features: 1) Enhance all logger calls to include exc_info for improved error tracing.

Fixes: 1) Correct format strings in `logger` calls to avoid using f-strings and replace with comma-delimited logging arguments; 2) Remove unused imports including `traceback` and `gettext_lazy`.

Extra: Consolidate logging practices across multiple modules for better consistency and maintainability.
This commit is contained in:
Egor Pavlovich Gorbunov 2025-11-04 15:41:07 +03:00
parent 5058fb1c18
commit a7af054631
10 changed files with 21 additions and 31 deletions

View file

@ -1,5 +1,4 @@
import logging
import traceback
from typing import Optional
import requests
@ -63,7 +62,7 @@ class AmoCRM:
payload["code"] = self.authorization_code
r = requests.post(f"{self.base}/oauth2/access_token", json=payload, timeout=15)
if not is_status_code_success(r.status_code):
logger.error(f"Unable to get AMO access token: {r.status_code} {r.text}")
logger.error("Unable to get AMO access token: %s %s", r.status_code, r.text)
raise CRMException("Unable to get AMO access token")
data = r.json()
self.access_token = data["access_token"]
@ -111,8 +110,7 @@ class AmoCRM:
r.raise_for_status()
body = r.json()
except requests.exceptions.RequestException as rex:
logger.error(f"Unable to get company info with FNS: {rex}")
logger.error(traceback.format_exc())
logger.error("Unable to get company info with FNS: %s", rex, exc_info=True)
return ""
ul = body.get("ЮЛ")
@ -161,8 +159,7 @@ class AmoCRM:
return None
except requests.exceptions.RequestException as rex:
logger.error(f"Unable to create a company in AmoCRM: {rex}")
logger.error(traceback.format_exc())
logger.error("Unable to create a company in AmoCRM: %s", rex, exc_info=True)
raise CRMException("Unable to create a company in AmoCRM") from rex
def process_order_changes(self, order: Order) -> str:

View file

@ -1,7 +1,6 @@
import datetime
import json
import logging
import traceback
from contextlib import suppress
from typing import Any, Optional, Self, Iterable
@ -1649,8 +1648,13 @@ class Order(ExportModelOperationsMixin("order"), NiceModel): # type: ignore [mi
crm_integration.process_order_changes(self)
return True
except Exception as e:
logger.error(f"failed to trigger CRM integration {crm_link.crm.name} for order {self.uuid}: {e}")
logger.error(traceback.format_exc())
logger.error(
"failed to trigger CRM integration %s for order %s: %s",
crm_link.crm.name,
self.uuid,
str(e),
exc_info=True,
)
return False
else:
crm = CustomerRelationshipManagementProvider.objects.get(default=True)
@ -1659,8 +1663,9 @@ class Order(ExportModelOperationsMixin("order"), NiceModel): # type: ignore [mi
crm_integration.process_order_changes(self)
return True
except Exception as e:
logger.error(f"failed to trigger CRM integration {crm.name} for order {self.uuid}: {e}")
logger.error(traceback.format_exc())
logger.error(
"failed to trigger CRM integration %s for order %s: %s", crm.name, self.uuid, str(e), exc_info=True
)
return False
@property

View file

@ -9,7 +9,6 @@ from django.dispatch import receiver
from django.utils.crypto import get_random_string
from django.utils.http import urlsafe_base64_decode
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
from sentry_sdk import capture_exception
from core.crm import any_crm_integrations
@ -70,7 +69,7 @@ def create_promocode_on_user_referring(instance: User, created: bool, **kwargs:
)
except Exception as e:
capture_exception(e)
logger.error(_(f"error during promocode creation: {e!s}"))
logger.error("Could not create PromoCode: %s", str(e))
# noinspection PyUnusedLocal

View file

@ -46,9 +46,9 @@ def update_products_task() -> tuple[bool, str]:
try:
vendor.update_stock()
except VendorInactiveError:
logger.info(f"Skipping {vendor.__str__} due to inactivity")
logger.info("Skipping %s due to inactivity", str(vendor))
except Exception as e:
logger.warning(f"Skipping {vendor.__str__} due to error: {e!s}")
logger.warning("Skipping %s due to error: %s", str(vendor), str(e))
delete_stale()
@ -177,7 +177,7 @@ def process_promotions() -> tuple[bool, str]:
)
response.raise_for_status()
except Exception as e:
logger.warning(f"Couldn't fetch holiday data for {checked_date}: {e!s}")
logger.warning("Couldn't fetch holiday data for %s: %s", checked_date, str(e))
return False, f"Couldn't fetch holiday data for {checked_date}: {e!s}"
holidays = response.json()
if holidays:

View file

@ -52,5 +52,5 @@ def set_default_cache() -> None:
for json_file in data_dir.glob("*.json"):
with json_file.open("r", encoding="utf-8") as f:
data = json.load(f)
logger.info(f"Setting cache for {json_file.stem}")
logger.info("Setting cache for %s", json_file.stem)
cache.set(json_file.stem, data, timeout=28800)

View file

@ -113,7 +113,7 @@ class AbstractVendor:
if settings.DEBUG:
logger.debug(message)
case LogLevel.TRACE:
logger.debug(f"[TRACE] {message}")
logger.debug("[TRACE] %s", message)
case LogLevel.INFO:
logger.info(message)
case LogLevel.WARNING:

View file

@ -1,5 +1,4 @@
import logging
import traceback
from os import getenv
from constance import config
@ -109,7 +108,6 @@ class GrapheneLoggingErrorsDebugMiddleware:
if any(isinstance(e, error_type) for error_type in self.WARNING_ONLY_ERRORS):
logger.warning(str(e))
else:
logger.error(str(e))
logger.error(traceback.format_exc())
logger.error(str(e), exc_info=True)
capture_exception(e)
raise e

View file

@ -71,7 +71,6 @@ class CallbackAPIView(APIView):
"""
def post(self, request: Request, *args: list[Any], **kwargs: dict[Any, Any]) -> Response:
logger.debug(f"{request.__dict__}\n")
try:
gateway = kwargs.get("gateway", "")
# noinspection PyUnreachableCode

View file

@ -1,5 +1,4 @@
import logging
import traceback
from django.contrib import auth
from django.contrib.auth.base_user import BaseUserManager
@ -48,8 +47,7 @@ class UserManager(BaseUserManager):
user.save()
return user
except Exception as e:
logger.error(e)
logger.error(traceback.format_exc())
logger.error(e, exc_info=True)
# noinspection PyUnusedLocal
def _create_user(self, email, password, **extra_fields):

View file

@ -180,8 +180,6 @@ class TokenObtainPairSerializer(TokenObtainSerializer):
def validate(self, attrs: dict[str, Any]) -> dict[str, str]:
data = super().validate(attrs)
logger.debug("Data validated")
if self.user is None:
raise ValidationError(_("no active account"))
@ -191,16 +189,12 @@ class TokenObtainPairSerializer(TokenObtainSerializer):
data["access"] = str(refresh.access_token) # type: ignore [attr-defined]
data["user"] = UserSerializer(self.user).data
logger.debug("Data formed")
if api_settings.UPDATE_LAST_LOGIN:
if not self.user:
raise ValidationError(_("no active account"))
# noinspection PyTypeChecker
update_last_login(User, self.user)
logger.debug("Updated last login")
logger.debug("Returning data")
return data