Skip to content

Commit 188c146

Browse files
ahoblitzclaude
andcommitted
refactor: optimize logging performance and modernize string formatting
- Replace f-strings with % formatting in logging calls for lazy evaluation - Convert .format() to f-strings in server/models.py __repr__ methods - Add test_venv/ to .gitignore - Improves performance by avoiding string formatting when log levels are disabled 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 72b2ee7 commit 188c146

File tree

8 files changed

+32
-43
lines changed

8 files changed

+32
-43
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ __pycache__
66
.pytest_cache
77
.ruff_cache
88
.venv
9+
test_venv/
910
coverage.xml
1011
.nox
1112
spec.json

src/a2a/server/events/event_consumer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ async def consume_one(self) -> Event:
6262
InternalError(message='Agent did not return any response')
6363
) from e
6464

65-
logger.debug(f'Dequeued event of type: {type(event)} in consume_one.')
65+
logger.debug('Dequeued event of type: %s in consume_one.', type(event))
6666

6767
self.queue.task_done()
6868

@@ -95,7 +95,7 @@ async def consume_all(self) -> AsyncGenerator[Event]:
9595
self.queue.dequeue_event(), timeout=self._timeout
9696
)
9797
logger.debug(
98-
f'Dequeued event of type: {type(event)} in consume_all.'
98+
'Dequeued event of type: %s in consume_all.', type(event)
9999
)
100100
self.queue.task_done()
101101
logger.debug(

src/a2a/server/events/event_queue.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ async def enqueue_event(self, event: Event) -> None:
5454
logger.warning('Queue is closed. Event will not be enqueued.')
5555
return
5656

57-
logger.debug(f'Enqueuing event of type: {type(event)}')
57+
logger.debug('Enqueuing event of type: %s', type(event))
5858

5959
# Make sure to use put instead of put_nowait to avoid blocking the event loop.
6060
await self.queue.put(event)
@@ -98,13 +98,13 @@ async def dequeue_event(self, no_wait: bool = False) -> Event:
9898
logger.debug('Attempting to dequeue event (no_wait=True).')
9999
event = self.queue.get_nowait()
100100
logger.debug(
101-
f'Dequeued event (no_wait=True) of type: {type(event)}'
101+
'Dequeued event (no_wait=True) of type: %s', type(event)
102102
)
103103
return event
104104

105105
logger.debug('Attempting to dequeue event (waiting).')
106106
event = await self.queue.get()
107-
logger.debug(f'Dequeued event (waited) of type: {type(event)}')
107+
logger.debug('Dequeued event (waited) of type: %s', type(event))
108108
return event
109109

110110
def task_done(self) -> None:

src/a2a/server/models.py

Lines changed: 12 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -147,14 +147,9 @@ def task_metadata(cls) -> Mapped[dict[str, Any] | None]:
147147
@override
148148
def __repr__(self) -> str:
149149
"""Return a string representation of the task."""
150-
repr_template = (
151-
'<{CLS}(id="{ID}", context_id="{CTX_ID}", status="{STATUS}")>'
152-
)
153-
return repr_template.format(
154-
CLS=self.__class__.__name__,
155-
ID=self.id,
156-
CTX_ID=self.context_id,
157-
STATUS=self.status,
150+
return (
151+
f'<{self.__class__.__name__}(id="{self.id}", '
152+
f'context_id="{self.context_id}", status="{self.status}")>'
158153
)
159154

160155

@@ -188,12 +183,9 @@ class TaskModel(TaskMixin, base): # type: ignore
188183
@override
189184
def __repr__(self) -> str:
190185
"""Return a string representation of the task."""
191-
repr_template = '<TaskModel[{TABLE}](id="{ID}", context_id="{CTX_ID}", status="{STATUS}")>'
192-
return repr_template.format(
193-
TABLE=table_name,
194-
ID=self.id,
195-
CTX_ID=self.context_id,
196-
STATUS=self.status,
186+
return (
187+
f'<TaskModel[{table_name}](id="{self.id}", '
188+
f'context_id="{self.context_id}", status="{self.status}")>'
197189
)
198190

199191
# Set a dynamic name for better debugging
@@ -221,11 +213,9 @@ class PushNotificationConfigMixin:
221213
@override
222214
def __repr__(self) -> str:
223215
"""Return a string representation of the push notification config."""
224-
repr_template = '<{CLS}(task_id="{TID}", config_id="{CID}")>'
225-
return repr_template.format(
226-
CLS=self.__class__.__name__,
227-
TID=self.task_id,
228-
CID=self.config_id,
216+
return (
217+
f'<{self.__class__.__name__}(task_id="{self.task_id}", '
218+
f'config_id="{self.config_id}")>'
229219
)
230220

231221

@@ -241,11 +231,9 @@ class PushNotificationConfigModel(PushNotificationConfigMixin, base): # type: i
241231
@override
242232
def __repr__(self) -> str:
243233
"""Return a string representation of the push notification config."""
244-
repr_template = '<PushNotificationConfigModel[{TABLE}](task_id="{TID}", config_id="{CID}")>'
245-
return repr_template.format(
246-
TABLE=table_name,
247-
TID=self.task_id,
248-
CID=self.config_id,
234+
return (
235+
f'<PushNotificationConfigModel[{table_name}]('
236+
f'task_id="{self.task_id}", config_id="{self.config_id}")>'
249237
)
250238

251239
PushNotificationConfigModel.__name__ = (

src/a2a/server/tasks/database_task_store.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ async def save(self, task: Task) -> None:
124124
db_task = self._to_orm(task)
125125
async with self.async_session_maker.begin() as session:
126126
await session.merge(db_task)
127-
logger.debug(f'Task {task.id} saved/updated successfully.')
127+
logger.debug('Task %s saved/updated successfully.', task.id)
128128

129129
async def get(self, task_id: str) -> Task | None:
130130
"""Retrieves a task from the database by ID."""
@@ -135,10 +135,10 @@ async def get(self, task_id: str) -> Task | None:
135135
task_model = result.scalar_one_or_none()
136136
if task_model:
137137
task = self._from_orm(task_model)
138-
logger.debug(f'Task {task_id} retrieved successfully.')
138+
logger.debug('Task %s retrieved successfully.', task_id)
139139
return task
140140

141-
logger.debug(f'Task {task_id} not found in store.')
141+
logger.debug('Task %s not found in store.', task_id)
142142
return None
143143

144144
async def delete(self, task_id: str) -> None:
@@ -151,8 +151,8 @@ async def delete(self, task_id: str) -> None:
151151
# Commit is automatic when using session.begin()
152152

153153
if result.rowcount > 0:
154-
logger.info(f'Task {task_id} deleted successfully.')
154+
logger.info('Task %s deleted successfully.', task_id)
155155
else:
156156
logger.warning(
157-
f'Attempted to delete nonexistent task with id: {task_id}'
157+
'Attempted to delete nonexistent task with id: %s', task_id
158158
)

src/a2a/utils/error_handlers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ async def wrapper(*args: Any, **kwargs: Any) -> Response:
8181
content={'message': error.message}, status_code=http_code
8282
)
8383
except Exception as e: # noqa: BLE001
84-
logger.log(logging.ERROR, f'Unknown error occurred {e}')
84+
logger.log(logging.ERROR, 'Unknown error occurred %s', e)
8585
return JSONResponse(
8686
content={'message': 'unknown exception'}, status_code=500
8787
)

src/a2a/utils/helpers.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ def decorator(function: Callable) -> Callable:
142142
async def async_wrapper(self: Any, *args, **kwargs) -> Any:
143143
if not expression(self):
144144
final_message = error_message or str(expression)
145-
logger.error(f'Unsupported Operation: {final_message}')
145+
logger.error('Unsupported Operation: %s', final_message)
146146
raise ServerError(
147147
UnsupportedOperationError(message=final_message)
148148
)
@@ -154,7 +154,7 @@ async def async_wrapper(self: Any, *args, **kwargs) -> Any:
154154
def sync_wrapper(self: Any, *args, **kwargs) -> Any:
155155
if not expression(self):
156156
final_message = error_message or str(expression)
157-
logger.error(f'Unsupported Operation: {final_message}')
157+
logger.error('Unsupported Operation: %s', final_message)
158158
raise ServerError(
159159
UnsupportedOperationError(message=final_message)
160160
)
@@ -186,7 +186,7 @@ def decorator(function):
186186
async def wrapper(self, *args, **kwargs):
187187
if not expression(self):
188188
final_message = error_message or str(expression)
189-
logger.error(f'Unsupported Operation: {final_message}')
189+
logger.error('Unsupported Operation: %s', final_message)
190190
raise ServerError(
191191
UnsupportedOperationError(message=final_message)
192192
)

src/a2a/utils/telemetry.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ def trace_function( # noqa: PLR0915
171171
is_async_func = inspect.iscoroutinefunction(func)
172172

173173
logger.debug(
174-
f'Start tracing for {actual_span_name}, is_async_func {is_async_func}'
174+
'Start tracing for %s, is_async_func %s', actual_span_name, is_async_func
175175
)
176176

177177
@functools.wraps(func)
@@ -196,7 +196,7 @@ async def async_wrapper(*args, **kwargs) -> Any:
196196
# asyncio.CancelledError extends from BaseException
197197
except asyncio.CancelledError as ce:
198198
exception = None
199-
logger.debug(f'CancelledError in span {actual_span_name}')
199+
logger.debug('CancelledError in span %s', actual_span_name)
200200
span.record_exception(ce)
201201
raise
202202
except Exception as e:
@@ -212,7 +212,7 @@ async def async_wrapper(*args, **kwargs) -> Any:
212212
)
213213
except Exception:
214214
logger.exception(
215-
f'attribute_extractor error in span {actual_span_name}'
215+
'attribute_extractor error in span %s', actual_span_name
216216
)
217217
return result
218218

@@ -246,7 +246,7 @@ def sync_wrapper(*args, **kwargs) -> Any:
246246
)
247247
except Exception:
248248
logger.exception(
249-
f'attribute_extractor error in span {actual_span_name}'
249+
'attribute_extractor error in span %s', actual_span_name
250250
)
251251
return result
252252

@@ -307,7 +307,7 @@ def not_traced_method(self):
307307
pass
308308
```
309309
"""
310-
logger.debug(f'Trace all class {include_list}, {exclude_list}')
310+
logger.debug('Trace all class %s, %s', include_list, exclude_list)
311311
exclude_list = exclude_list or []
312312

313313
def decorator(cls: Any) -> Any:

0 commit comments

Comments
 (0)