From 377f397cc8c4edc0aace63795857aa4265d749c8 Mon Sep 17 00:00:00 2001 From: liqiang-fit2cloud Date: Thu, 11 Dec 2025 17:20:01 +0800 Subject: [PATCH] refactor: log tool execution duration --- apps/common/utils/tool_code.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/apps/common/utils/tool_code.py b/apps/common/utils/tool_code.py index 16c1f2e30..a5b29af1c 100644 --- a/apps/common/utils/tool_code.py +++ b/apps/common/utils/tool_code.py @@ -12,7 +12,9 @@ import pwd import resource import getpass import random +import time import uuid_utils.compat as uuid +from contextlib import contextmanager from common.utils.logger import maxkb_logger from django.utils.translation import gettext_lazy as _ from maxkb.const import BASE_DIR, CONFIG @@ -108,7 +110,8 @@ sys.stdout.flush() with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=True) as f: f.write(_exec_code) f.flush() - subprocess_result = self._exec(f.name) + with execution_timer(_id): + subprocess_result = self._exec(f.name) if subprocess_result.returncode != 0: raise Exception(subprocess_result.stderr or subprocess_result.stdout or "Unknown exception occurred") lines = subprocess_result.stdout.splitlines() @@ -244,3 +247,12 @@ exec({dedent(code)!a}) for server, config in servers.items(): if config.get('transport') not in ['sse', 'streamable_http']: raise Exception(_('Only support transport=sse or transport=streamable_http')) + + +@contextmanager +def execution_timer(id=""): + start = time.perf_counter() + try: + yield + finally: + maxkb_logger.debug(f"Tool execution({id}) takes {time.perf_counter() - start:.6f} seconds.") \ No newline at end of file