Skip to content

Commit da202e0

Browse files
frostmingclaude
andauthored
refactor: use module-scoped loggers instead of the root logger (#195)
Replace bare logging.* calls in the library with a per-module `_logger = logging.getLogger(__name__)` so records are emitted under the `acp.*` namespace and can be configured or silenced by applications. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent dbd4bdb commit da202e0

4 files changed

Lines changed: 22 additions & 14 deletions

File tree

‎src/acp/connection.py‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
from .task import MessageSender, TaskSupervisor
1919
from .telemetry import span_context
2020

21+
_logger = logging.getLogger(__name__)
22+
2123
JsonValue = Any
2224
MethodHandler = Callable[[str, JsonValue | None, bool], Awaitable[JsonValue | None]]
2325

@@ -107,7 +109,7 @@ async def main_loop(self) -> None:
107109
try:
108110
await self._receive_loop()
109111
except Exception as exc:
110-
logging.exception("Connection main loop failed", exc_info=exc)
112+
_logger.exception("Connection main loop failed", exc_info=exc)
111113
self._on_receive_error(None, exc) # type: ignore[arg-type]
112114
raise
113115

@@ -190,7 +192,7 @@ def _notify_observers(self, direction: StreamDirection, message: dict[str, Any])
190192
try:
191193
result = observer(event)
192194
except Exception:
193-
logging.exception("Stream observer failed", exc_info=True)
195+
_logger.exception("Stream observer failed", exc_info=True)
194196
continue
195197
if inspect.isawaitable(result):
196198
self._tasks.create(
@@ -200,7 +202,7 @@ def _notify_observers(self, direction: StreamDirection, message: dict[str, Any])
200202
)
201203

202204
def _on_observer_error(self, task: asyncio.Task[Any], exc: BaseException) -> None:
203-
logging.exception("Stream observer coroutine failed", exc_info=exc)
205+
_logger.exception("Stream observer coroutine failed", exc_info=exc)
204206

205207
def _track_incoming(self, request_id: Any, task: asyncio.Task[Any]) -> None:
206208
# A ``$/cancel_request`` can only name a valid request id, and Python would alias an invalid
@@ -237,7 +239,7 @@ def _send_cancel_request(self, request_id: int) -> None:
237239
)
238240

239241
def _on_cancel_request_error(self, task: asyncio.Task[Any], exc: BaseException) -> None:
240-
logging.debug("Failed to send %s", _CANCEL_REQUEST_METHOD, exc_info=exc)
242+
_logger.debug("Failed to send %s", _CANCEL_REQUEST_METHOD, exc_info=exc)
241243

242244
async def _run_request(
243245
self, message: dict[str, Any], handler: asyncio.Future[dict[str, Any]] | None = None
@@ -257,7 +259,7 @@ async def _run_request(
257259
except ConnectionError:
258260
if self._closed or self._disconnected:
259261
# The connection went away while the handler was running; nobody can receive it.
260-
logging.debug("Dropping response for request %r: connection closed", message["id"])
262+
_logger.debug("Dropping response for request %r: connection closed", message["id"])
261263
return
262264
raise
263265
self._notify_observers(StreamDirection.OUTGOING, payload)
@@ -284,7 +286,7 @@ async def _execute_request(self, message: dict[str, Any]) -> dict[str, Any]:
284286
except ValidationError as exc:
285287
payload["error"] = RequestError.invalid_params({"errors": exc.errors()}).to_error_obj()
286288
except Exception as exc:
287-
logging.exception(
289+
_logger.exception(
288290
"Unhandled error while handling request method=%s",
289291
method,
290292
exc_info=exc,
@@ -302,7 +304,7 @@ async def _run_notification(self, message: dict[str, Any]) -> None:
302304
try:
303305
await self._handler(method, message.get("params"), True)
304306
except Exception as exc:
305-
logging.exception(
307+
_logger.exception(
306308
"Unhandled error while handling notification method=%s",
307309
method,
308310
exc_info=exc,
@@ -335,11 +337,11 @@ def _handle_response(self, message: dict[str, Any]) -> None:
335337
self._pending.pop(request_id, None)
336338

337339
def _on_receive_error(self, task: asyncio.Task[Any], exc: BaseException) -> None:
338-
logging.exception("Receive loop failed", exc_info=exc)
340+
_logger.exception("Receive loop failed", exc_info=exc)
339341
self._disconnect()
340342

341343
def _on_task_error(self, task: asyncio.Task[Any], exc: BaseException) -> None:
342-
logging.exception("Background task failed", exc_info=exc)
344+
_logger.exception("Background task failed", exc_info=exc)
343345

344346
def _disconnect(self) -> None:
345347
if self._disconnected:

‎src/acp/stdio.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
from .interfaces import Agent, Client
1919
from .transports import spawn_stdio_transport
2020

21+
_logger = logging.getLogger(__name__)
22+
2123
__all__ = [
2224
"spawn_agent_process",
2325
"spawn_client_process",
@@ -76,7 +78,7 @@ def write(self, data: bytes) -> None: # type: ignore[override]
7678
sys.stdout.buffer.write(data)
7779
sys.stdout.buffer.flush()
7880
except Exception:
79-
logging.exception("Error writing to stdout")
81+
_logger.exception("Error writing to stdout")
8082

8183
def can_write_eof(self) -> bool: # type: ignore[override]
8284
return False

‎src/acp/task/supervisor.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
from collections.abc import Awaitable, Callable
66
from typing import Any
77

8+
_logger = logging.getLogger(__name__)
9+
810
__all__ = ["TaskSupervisor"]
911

1012
ErrorHandler = Callable[[asyncio.Task[Any], BaseException], None]
@@ -55,16 +57,16 @@ def _on_done(self, task: asyncio.Task[Any], on_error: ErrorHandler | None) -> No
5557
on_error(task, exc)
5658
handled = True
5759
except Exception:
58-
logging.exception("Error in %s task-specific error handler", self._source)
60+
_logger.exception("Error in %s task-specific error handler", self._source)
5961
if not handled:
6062
for handler in self._error_handlers:
6163
try:
6264
handler(task, exc)
6365
handled = True
6466
except Exception:
65-
logging.exception("Error in %s supervisor error handler", self._source)
67+
_logger.exception("Error in %s supervisor error handler", self._source)
6668
if not handled:
67-
logging.exception("Unhandled error in %s task", self._source)
69+
_logger.exception("Unhandled error in %s task", self._source)
6870

6971
async def shutdown(self) -> None:
7072
self._closed = True

‎src/acp/ws/server.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
from ..experimental.negotiation import AgentProtocolRouter
1919
from ..http.server import AgentFactory
2020

21+
_logger = logging.getLogger(__name__)
22+
2123
__all__ = ["handle_websocket"]
2224

2325

@@ -41,7 +43,7 @@ async def receive(self) -> dict[str, Any] | None:
4143
if event.get("text") is None:
4244
if event.get("bytes") is not None and not self._warned_binary:
4345
self._warned_binary = True
44-
logging.warning("Ignoring binary WebSocket frame; ACP messages must be sent as text frames")
46+
_logger.warning("Ignoring binary WebSocket frame; ACP messages must be sent as text frames")
4547
continue
4648
try:
4749
message = decode_message(event["text"])

0 commit comments

Comments
 (0)