Skip to content

Commit

Permalink
Merge pull request #238 from ecmwf-projects/COPDS-2390-reduce-traceba…
Browse files Browse the repository at this point in the history
…ck-length-in-logs

Reduce tracebacks length in logs
  • Loading branch information
mcucchi9 authored Jan 28, 2025
2 parents cbf26c2 + da1ae20 commit 781e850
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 40 deletions.
7 changes: 7 additions & 0 deletions cads_processing_api_service/clients.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ class DatabaseClient(ogc_api_processes_fastapi.clients.BaseClient):
"DeleteJob": "Dismiss the job identifed by `job_id`.",
}

@exceptions.exception_logger
def get_processes(
self,
limit: int | None = fastapi.Query(10, ge=1, le=10000),
Expand Down Expand Up @@ -139,6 +140,7 @@ def get_processes(
process_list._pagination_query_params = pagination_query_params
return process_list

@exceptions.exception_logger
def get_process(
self,
response: fastapi.Response,
Expand Down Expand Up @@ -188,6 +190,7 @@ def get_process(

return process_description

@exceptions.exception_logger
def post_process_execution(
self,
request: fastapi.Request,
Expand Down Expand Up @@ -327,6 +330,7 @@ def post_process_execution(
status_info.message = job_message
return status_info

@exceptions.exception_logger
def get_jobs(
self,
processID: list[str] | None = fastapi.Query(None),
Expand Down Expand Up @@ -460,6 +464,7 @@ def get_jobs(

return job_list

@exceptions.exception_logger
def get_job(
self,
job_id: str = fastapi.Path(...),
Expand Down Expand Up @@ -594,6 +599,7 @@ def get_job(
status_info = utils.make_status_info(job=job, **kwargs)
return status_info

@exceptions.exception_logger
def get_job_results(
self,
job_id: str = fastapi.Path(...),
Expand Down Expand Up @@ -656,6 +662,7 @@ def get_job_results(
handle_download_metrics(job.process_id, results)
return results

@exceptions.exception_logger
def delete_job(
self,
job_id: str = fastapi.Path(...),
Expand Down
1 change: 1 addition & 0 deletions cads_processing_api_service/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from . import adaptors, db_utils, exceptions, models, utils


@exceptions.exception_logger
def apply_constraints(
process_id: str = fastapi.Path(...),
execution_content: models.Execute = fastapi.Body(...),
Expand Down
3 changes: 2 additions & 1 deletion cads_processing_api_service/costing.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import cads_catalogue
import fastapi

from . import adaptors, costing, db_utils, models, utils
from . import adaptors, costing, db_utils, exceptions, models, utils

COST_THRESHOLDS = {"api": "max_costs", "ui": "max_costs_portal"}

Expand All @@ -32,6 +32,7 @@ class RequestOrigin(str, enum.Enum):
ui = "ui"


@exceptions.exception_logger
def estimate_cost(
process_id: str = fastapi.Path(...),
request_origin: RequestOrigin = fastapi.Query("api"),
Expand Down
62 changes: 24 additions & 38 deletions cads_processing_api_service/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
# See the License for the specific language governing permissions and
# limitations under the License

import functools
import traceback
from typing import Any, Callable

import attrs
import fastapi
Expand Down Expand Up @@ -63,26 +65,28 @@ class RateLimitExceeded(ogc_api_processes_fastapi.exceptions.OGCAPIException):
retry_after: int = 0


def get_exc_group_tb(exc_traceback: list[str]) -> list[str]:
"""Get and return only the Exception Group Traceback.
Parameters
----------
exc_traceback : list[str]
List of lines in the traceback.
Returns
-------
list[str]
List of lines in the traceback.
"""
exc_group_tb = []
if "Exception Group Traceback" in exc_traceback[0]:
exc_group_tb.append(exc_traceback[0])
for line in exc_traceback[1:]:
if line.lstrip(" ").startswith(("+", "|")):
exc_group_tb.append(line)
return exc_group_tb
def exception_logger(f: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(f)
def wrapper(*args: Any, **kwargs: Any) -> Any:
try:
res = f(*args, **kwargs)
except requests.exceptions.ReadTimeout:
raise
except Exception as exc:
if isinstance(exc, ogc_api_processes_fastapi.exceptions.OGCAPIException):
exc_title = exc.title
else:
exc_title = "internal server error"
logger.error(
exc_title,
exception="".join(
traceback.TracebackException.from_exception(exc).format()
),
)
raise
return res

return wrapper


def format_exception_content(
Expand Down Expand Up @@ -135,11 +139,6 @@ def exception_handler(
fastapi.responses.JSONResponse
JSON response.
"""
logger.error(
exc.title,
exception="".join(traceback.TracebackException.from_exception(exc).format()),
url=str(request.url),
)
out = fastapi.responses.JSONResponse(
status_code=exc.status_code,
content=format_exception_content(exc=exc, request=request),
Expand All @@ -164,11 +163,6 @@ def rate_limit_exceeded_exception_handler(
fastapi.responses.JSONResponse
JSON response.
"""
logger.error(
exc.title,
exception="".join(traceback.TracebackException.from_exception(exc).format()),
url=str(request.url),
)
out = fastapi.responses.JSONResponse(
status_code=exc.status_code,
content=format_exception_content(exc=exc, request=request),
Expand Down Expand Up @@ -223,14 +217,6 @@ def general_exception_handler(
-------
fastapi.responses.JSONResponse
"""
exc_traceback = list(traceback.TracebackException.from_exception(exc).format())
exc_group_traceback = get_exc_group_tb(exc_traceback)
logger.error(
"internal server error",
exception="".join(
exc_group_traceback if exc_group_traceback else exc_traceback
),
)
out = fastapi.responses.JSONResponse(
status_code=fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR,
content=models.Exception(
Expand Down
3 changes: 2 additions & 1 deletion cads_processing_api_service/translators.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import fastapi
import structlog

from . import config
from . import config, exceptions

SETTINGS = config.settings

Expand Down Expand Up @@ -335,6 +335,7 @@ def format_api_request(
return api_request


@exceptions.exception_logger
def get_api_request(
process_id: str = fastapi.Path(...),
request: dict[str, Any] = fastapi.Body(...),
Expand Down

0 comments on commit 781e850

Please sign in to comment.