From 8cde76e70a567dc99f74f827a7ce51658f1b9dcf Mon Sep 17 00:00:00 2001 From: Alexey Kartashov Date: Mon, 9 Dec 2024 14:45:34 +0100 Subject: [PATCH] improvement(error_handlers): Add context dump to the exceptions This commit adds additional information and trace ids to the exception that occur inside the API calls, allowing to collect more information about the error, including the request data. Fixes #492 --- argus/backend/error_handlers.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/argus/backend/error_handlers.py b/argus/backend/error_handlers.py index 30b5b5ba..c3e83abe 100644 --- a/argus/backend/error_handlers.py +++ b/argus/backend/error_handlers.py @@ -1,4 +1,7 @@ +import base64 +from hashlib import sha256 import logging +import os from traceback import format_exception from flask import request @@ -12,14 +15,24 @@ class DataValidationError(APIException): pass def handle_api_exception(exception: Exception): + trace_id = base64.encodebytes(sha256(os.urandom(64)).digest()).decode(encoding="utf-8").strip() if issubclass(exception.__class__, APIException): + LOGGER.info("TraceId: %s", trace_id) LOGGER.info("Endpoint %s responded with error %s: %s", request.endpoint, exception.__class__.__name__, str(exception)) + LOGGER.info("Headers\n%s", request.headers) + LOGGER.info("Request Data Start\n%s\nRequest Data End", request.json if request.is_json else request.get_data(as_text=True)) + LOGGER.info("TraceId: %s", trace_id) else: + LOGGER.error("TraceId: %s", trace_id) LOGGER.error("Exception in %s\n%s", request.endpoint, "".join(format_exception(exception))) + LOGGER.error("Headers\n%s", request.headers) + LOGGER.error("Request Data Start\n%s\nRequest Data End", request.json if request.is_json else request.get_data(as_text=True)) + LOGGER.error("TraceId: %s", trace_id) return { "status": "error", "response": { + "trace_id": trace_id, "exception": exception.__class__.__name__, "arguments": exception.args }