Skip to content

Commit 2cca61f

Browse files
committed
refactor(portaswitch): improve logging efficiency with message truncation and remove redundant debug logs
1 parent 04117cf commit 2cca61f

File tree

4 files changed

+25
-21
lines changed

4 files changed

+25
-21
lines changed

app/bss/adapters/portaswitch/api/account.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
import logging
21
from datetime import datetime
32
from typing import Final, List, Union, Iterator
43

54
import requests
5+
from jose import jwt
6+
67
from bss.adapters.portaswitch.config import PortaSwitchSettings
78
from bss.adapters.portaswitch.types import PortaSwitchMailboxMessageFlag, PortaSwitchMailboxMessageFlagAction
89
from bss.http_api import HTTPAPIConnector, AuthSessionData
9-
from jose import jwt
1010

1111
DEFAULT_CHUNK_SIZE: Final[int] = 8192
1212

@@ -40,7 +40,6 @@ def __send_request(
4040
:response (dict): The API method execution result.
4141
4242
"""
43-
logging.debug(f"Sending Account.API request: {module}/{method}/{params}")
4443

4544
headers = None
4645
if access_token:
@@ -54,7 +53,6 @@ def __send_request(
5453
stream=stream,
5554
)
5655

57-
logging.debug(f"Processing the Account.API result: {module}/{method}/{params}: \n {result}")
5856
return result
5957

6058
def add_auth_info(self, url: str, request_params: dict, auth_session: AuthSessionData) -> dict:
@@ -284,7 +282,8 @@ def get_phone_directory_list(self, access_token: str, page: int, items_per_page:
284282
},
285283
access_token=access_token)
286284

287-
def get_phone_directory_info(self, access_token: str, i_ua_config_directory: str, page: int, items_per_page: int) -> dict:
285+
def get_phone_directory_info(self, access_token: str, i_ua_config_directory: str, page: int,
286+
items_per_page: int) -> dict:
288287
"""Return the phone directory info of the account.
289288
290289
Args:

app/bss/adapters/portaswitch/api/admin.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,6 @@ def _send_request(self, module: str, method: str, params: dict, turn_off_login:
183183
:response (object): The API method execution result.
184184
185185
"""
186-
logging.debug(f"Sending Admin.API request: {module}/{method}/{params}")
187-
188186
try:
189187
result = self.send_rest_request(
190188
method="POST",
@@ -212,5 +210,4 @@ def _send_request(self, module: str, method: str, params: dict, turn_off_login:
212210
else:
213211
raise error
214212

215-
logging.debug(f"Processing the Admin.API result: {module}/{method}/{params}: \n {result}")
216213
return result

app/bss/http_api.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,15 @@
11
import logging
2+
import threading
3+
import uuid
24
from abc import ABC, abstractmethod
3-
from typing import Optional
4-
5-
from pydantic import BaseModel, Field
65
from datetime import datetime, timedelta
6+
from typing import Optional
77

88
import requests
9+
from pydantic import BaseModel, Field
910

1011
from report_error import raise_webtrit_error
11-
import threading
12-
from request_trace import get_request_id
13-
import uuid
14-
15-
16-
# from bss.types import SignupExtAPIErrorCode as ExtAPIErrorCode
12+
from request_trace import get_request_id, truncate_log_message
1713

1814

1915
class APIUser(BaseModel):
@@ -124,7 +120,7 @@ def send_rest_request(self,
124120
try:
125121
logging.debug(f"Sending {method} request to {url} with parameters {params_final}")
126122
response = requests.request(method, url, **params_final)
127-
clean_text = response.text.replace("\n", " ")
123+
clean_text = truncate_log_message(response.text.replace("\n", " "))
128124
logging.debug(f"Received {response.status_code} {clean_text}")
129125
response.raise_for_status()
130126
return self.decode_response(response)
@@ -256,8 +252,8 @@ def send_rest_request(self,
256252
# we do not have an access token, need to log in first
257253
if hasattr(user, 'password') and user.password is None:
258254
raise_webtrit_error(401,
259-
error_message="Authentication session is closed, need to re-login",
260-
extra_error_code="access_token_expired")
255+
error_message="Authentication session is closed, need to re-login",
256+
extra_error_code="access_token_expired")
261257

262258
auth_session = self.login(user)
263259
self.store_auth_session(auth_session, user)

app/request_trace.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,21 @@
1212
from starlette.responses import StreamingResponse
1313
import traceback
1414

15+
MAX_LOG_MESSAGE_LENGTH = int(os.getenv("LOG_MAX_MESSAGE_LENGTH", "1000"))
16+
1517
# Add context variable for request ID
1618
current_request_id = contextvars.ContextVar('current_request_id', default="STARTUP")
1719

20+
21+
22+
def truncate_log_message(message: str, max_length: int = MAX_LOG_MESSAGE_LENGTH) -> str:
23+
"""Truncate log message to avoid logging excessively large payloads."""
24+
if message is None:
25+
return ""
26+
if len(message) <= max_length:
27+
return message
28+
return f"{message[:max_length]}... [truncated {len(message) - max_length} chars]"
29+
1830
class AddRequestID(logging.Filter):
1931
"""Logging filter that adds request_id to log records"""
2032
def filter(self, record):
@@ -78,7 +90,7 @@ def log_formatted_json(label: str, text):
7890
if len(text) == 0:
7991
logging.info(f"{label}: Empty")
8092
return
81-
logging.info(f"{label}: {text}")
93+
logging.info(f"{label}: {truncate_log_message(text)}")
8294
return
8395

8496
def log_info(req_body, res_body):

0 commit comments

Comments
 (0)