Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

feat(python-sdk): add logger option for request/debug logging (#1409)

Mish Ushakov8b8a224f8b83
diff --git a/.changeset/python-connection-logger.md b/.changeset/python-connection-logger.md
new file mode 100644
index 000000000..50d0353c2
--- /dev/null
+++ b/.changeset/python-connection-logger.md
@@ -0,0 +1,35 @@
+---
+"@e2b/python-sdk": patch
+---
+
+feat(python-sdk): add a `logger` option for request/debug logging
+
+You can now pass a standard library `logging.Logger` to `Sandbox.create` /
+`AsyncSandbox.create` (and the static `Sandbox.connect(sandbox_id, ...)`) to
+route that sandbox's request/response logs to your own logger. The logger is
+stored on the sandbox and propagates to all of its later operations —
+including control-plane calls such as `kill`, `pause`, `set_timeout`, and
+`get_info`. Matching the JavaScript SDK, `logger` is a construction-time option
+and is **not** a per-request parameter that those methods accept from the
+caller. The stdlib `logging.Logger` is used directly as the adapter instead of
+a custom interface.
+
+The logger is wired into the API client, the envd client, and the RPC
+(ConnectRPC) path. Mirroring the JS SDK: requests log at `INFO`, successful API
+and unary RPC responses at `INFO`, streamed RPC messages at `DEBUG`, and failed
+API responses (status >= 400) at `ERROR`. When no logger is supplied, the SDK
+emits no request/response logging at all (also matching the JS SDK).
+
+Volume content operations continue to accept `logger` per call via
+`VolumeApiParams`, matching the JS Volume API.
+
+```python
+import logging
+from e2b import Sandbox
+
+logging.basicConfig(level=logging.DEBUG)
+logger = logging.getLogger("my-app.e2b")
+
+sbx = Sandbox.create(logger=logger)
+sbx.commands.run("echo hello") # request/response logged via `logger`
+```
diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.py
index eed85ad1d..2a1e42d20 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -22,7 +22,45 @@ from e2b.exceptions import (
SandboxException,
)
-logger = logging.getLogger(__name__)
+
+def make_logging_event_hooks(log: Optional[logging.Logger]) -> dict:
+ """Build synchronous httpx ``event_hooks`` that log requests and responses
+ to the given ``logging.Logger``. Requests log at ``INFO``, successful
+ responses at ``INFO`` and responses with status >= 400 at ``ERROR``.
+
+ Returns no hooks when ``log`` is ``None`` so that nothing is logged unless a
+ logger was explicitly supplied."""
+ if log is None:
+ return {}
+
+ def on_request(request) -> None:
+ log.info(f"Request {request.method} {request.url}")
+
+ def on_response(response: Response) -> None:
+ if response.status_code >= 400:
+ log.error(f"Response {response.status_code}")
+ else:
+ log.info(f"Response {response.status_code}")
+
+ return {"request": [on_request], "response": [on_response]}
+
+
+def make_async_logging_event_hooks(log: Optional[logging.Logger]) -> dict:
+ """Asynchronous counterpart of :func:`make_logging_event_hooks`."""
+ if log is None:
+ return {}
+
+ async def on_request(request) -> None:
+ log.info(f"Request {request.method} {request.url}")
+
+ async def on_response(response: Response) -> None:
+ if response.status_code >= 400:
+ log.error(f"Response {response.status_code}")
+ else:
+ log.info(f"Response {response.status_code}")
+
+ return {"request": [on_request], "response": [on_response]}
+
limits = Limits(
max_keepalive_connections=int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS", "20")),
@@ -141,6 +179,8 @@ class ApiClient(AuthenticatedClient):
auth_header_name = "X-API-KEY"
prefix = ""
+ self._logger = config.logger
+
headers = {
**default_headers,
# Deprecated: send the access token alongside the API key when one
@@ -164,10 +204,7 @@ class ApiClient(AuthenticatedClient):
kwargs.pop("prefix", None)
httpx_args = {
- "event_hooks": {
- "request": [self._log_request],
- "response": [self._log_response],
- },
+ "event_hooks": self._logging_event_hooks(),
}
if transport is not None:
httpx_args["transport"] = transport
@@ -193,6 +230,9 @@ class ApiClient(AuthenticatedClient):
**kwargs,
)
+ def _logging_event_hooks(self) -> dict:
+ return make_logging_event_hooks(self._logger)
+
def _headers_with_auth(self) -> dict:
return {
**self._headers,
@@ -240,23 +280,8 @@ class ApiClient(AuthenticatedClient):
self._async_clients[loop] = client
return client
- def _log_request(self, request):
- logger.info(f"Request {request.method} {request.url}")
-
- def _log_response(self, response: Response):
- if response.status_code >= 400:
- logger.error(f"Response {response.status_code}")
- else:
- logger.info(f"Response {response.status_code}")
-
# We need to override the logging hooks for the async usage
class AsyncApiClient(ApiClient):
- async def _log_request(self, request):
- logger.info(f"Request {request.method} {request.url}")
-
- async def _log_response(self, response: Response):
- if response.status_code >= 400:
- logger.error(f"Response {response.status_code}")
- else:
- logger.info(f"Response {response.status_code}")
+ def _logging_event_hooks(self) -> dict:
+ return make_async_logging_event_hooks(self._logger)
diff --git a/packages/python-sdk/e2b/api/client_async/__init__.py b/packages/python-sdk/e2b/api/client_async/__init__.py
index 22bbea509..dd001a3a4 100644
--- a/packages/python-sdk/e2b/api/client_async/__init__.py
+++ b/packages/python-sdk/e2b/api/client_async/__init__.py
@@ -1,5 +1,4 @@
import asyncio
-import logging
import weakref
from typing import Dict, Optional, Tuple
@@ -10,8 +9,6 @@ from httpx._types import ProxyTypes
from e2b.api import AsyncApiClient, connection_retries, limits
from e2b.connection_config import ConnectionConfig
-logger = logging.getLogger(__name__)
-
TransportKey = Tuple[bool, Optional[ProxyTypes]]
@@ -32,16 +29,6 @@ class AsyncTransportWithLogger(httpx.AsyncHTTPTransport):
Dict[TransportKey, "AsyncTransportWithLogger"],
] = weakref.WeakKeyDictionary()
- async def handle_async_request(self, request):
- url = f"{request.url.scheme}://{request.url.host}{request.url.path}"
- logger.info(f"Request: {request.method} {url}")
- response = await super().handle_async_request(request)
-
- # data = connect.GzipCompressor.decompress(response.read()).decode()
- logger.info(f"Response: {response.status_code} {url}")
-
- return response
-
@property
def pool(self):
return self._pool
diff --git a/packages/python-sdk/e2b/api/client_sync/__init__.py b/packages/python-sdk/e2b/api/client_sync/__init__.py
index c4522aaed..41fb4f023 100644
--- a/packages/python-sdk/e2b/api/client_sync/__init__.py
+++ b/packages/python-sdk/e2b/api/client_sync/__init__.py
@@ -1,7 +1,6 @@
from typing import Dict, Optional, Tuple
import httpx
-import logging
import threading
from httpx._types import ProxyTypes
@@ -9,8 +8,6 @@ from httpx._types import ProxyTypes
from e2b.api import ApiClient, connection_retries, limits
from e2b.connection_config import ConnectionConfig
-logger = logging.getLogger(__name__)
-
TransportKey = Tuple[bool, Optional[ProxyTypes]]
@@ -25,16 +22,6 @@ def get_api_client(config: ConnectionConfig, **kwargs) -> ApiClient:
class TransportWithLogger(httpx.HTTPTransport):
_thread_local = threading.local()
- def handle_request(self, request):
- url = f"{request.url.scheme}://{request.url.host}{request.url.path}"
- logger.info(f"Request: {request.method} {url}")
- response = super().handle_request(request)
-
- # data = connect.GzipCompressor.decompress(response.read()).decode()
- logger.info(f"Response: {response.status_code} {url}")
-
- return response
-
@property
def pool(self):
return self._pool
diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.py
index d67a9151e..b9bef7102 100644
--- a/packages/python-sdk/e2b/connection_config.py
+++ b/packages/python-sdk/e2b/connection_config.py
@@ -1,3 +1,4 @@
+import logging
import os
from typing import cast, Optional, Dict, TypedDict
@@ -58,6 +59,18 @@ class ApiParams(TypedDict, total=False):
"""URL to connect to sandbox, defaults to `E2B_SANDBOX_URL` environment variable."""
+class ApiParamsWithLogger(ApiParams, total=False):
+ """:class:`ApiParams` plus the construction-time ``logger``.
+
+ Internal type returned by :meth:`ConnectionConfig.get_api_params` so that the
+ logger a sandbox was created/connected with keeps propagating to the
+ throwaway ``ConnectionConfig`` that instance control-plane methods rebuild.
+ Unlike :class:`ApiParams`, ``logger`` is not a public per-request option.
+ """
+
+ logger: Optional[logging.Logger]
+
+
class ConnectionConfig:
"""
Configuration for the connection to the API.
@@ -119,7 +132,9 @@ class ConnectionConfig:
integration: Optional[str] = None,
extra_sandbox_headers: Optional[Dict[str, str]] = None,
proxy: Optional[ProxyTypes] = None,
+ logger: Optional[logging.Logger] = None,
):
+ self.logger = logger
self.domain = domain or ConnectionConfig._domain()
self.debug = debug if debug is not None else ConnectionConfig._debug()
self.api_key = api_key or ConnectionConfig._api_key()
@@ -245,8 +260,14 @@ class ConnectionConfig:
integration,
)
+ # `logger` is a construction-time option rather than a per-request
+ # ApiParams field, but it must propagate to the throwaway
+ # ConnectionConfig that instance control-plane methods (kill, pause,
+ # set_timeout, get_info, connect, ...) rebuild from these params, so
+ # those requests keep logging with the logger the sandbox was created
+ # or connected with.
return dict(
- ApiParams(
+ ApiParamsWithLogger(
api_key=api_key if api_key is not None else self.api_key,
validate_api_key=(
validate_api_key
@@ -265,6 +286,7 @@ class ConnectionConfig:
if sandbox_url is not None
else cast(Optional[str], self._sandbox_url)
),
+ logger=self.logger,
)
)
diff --git a/packages/python-sdk/e2b/sandbox_async/commands/command.py b/packages/python-sdk/e2b/sandbox_async/commands/command.py
index 5bf32f616..93d6c3b9c 100644
--- a/packages/python-sdk/e2b/sandbox_async/commands/command.py
+++ b/packages/python-sdk/e2b/sandbox_async/commands/command.py
@@ -44,6 +44,7 @@ class Commands:
async_pool=pool,
json=True,
headers=connection_config.sandbox_headers,
+ logger=connection_config.logger,
)
async def list(
diff --git a/packages/python-sdk/e2b/sandbox_async/commands/pty.py b/packages/python-sdk/e2b/sandbox_async/commands/pty.py
index a9524ec82..db793f2d0 100644
--- a/packages/python-sdk/e2b/sandbox_async/commands/pty.py
+++ b/packages/python-sdk/e2b/sandbox_async/commands/pty.py
@@ -46,6 +46,7 @@ class Pty:
async_pool=pool,
json=True,
headers=connection_config.sandbox_headers,
+ logger=connection_config.logger,
)
async def kill(
diff --git a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
index 63306ebc3..e40be70e8 100644
--- a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
@@ -100,6 +100,7 @@ class Filesystem:
async_pool=pool,
json=True,
headers=connection_config.sandbox_headers,
+ logger=connection_config.logger,
)
@overload
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index 28ce5d4f3..791b9b360 100644
--- a/packages/python-sdk/e2b/sandbox_async/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -9,6 +9,8 @@ import httpx
from packaging.version import Version
from typing_extensions import Self, Unpack
+from e2b.api import make_async_logging_event_hooks
+from e2b.api.client.types import Unset
from e2b.api.client_async import get_envd_transport as get_transport
from e2b.connection_config import ApiParams, ConnectionConfig
from e2b.envd.api import ENVD_API_HEALTH_ROUTE, ahandle_envd_api_exception
@@ -108,6 +110,7 @@ class AsyncSandbox(SandboxApi):
base_url=self.envd_api_url,
transport=self._transport,
headers=self.connection_config.sandbox_headers,
+ event_hooks=make_async_logging_event_hooks(self.connection_config.logger),
)
self._filesystem = Filesystem(
self.envd_api_url,
@@ -181,6 +184,7 @@ class AsyncSandbox(SandboxApi):
network: Optional[SandboxNetworkOpts] = None,
lifecycle: Optional[SandboxLifecycle] = None,
volume_mounts: Optional[SandboxAsyncVolumeMount] = None,
+ logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> Self:
"""
@@ -198,6 +202,7 @@ class AsyncSandbox(SandboxApi):
:param network: Sandbox network configuration. ``allow_out``/``deny_out`` may also be a callable receiving a :class:`SandboxNetworkSelectorContext` (``ctx.all_traffic``, ``ctx.rules``) and returning a list of strings. Per-host transform rules are nested under ``network.rules``.
:param lifecycle: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``, or an object ``{"action": "pause"|"kill", "keep_memory": bool}`` where ``keep_memory`` (default ``True``) set to ``False`` makes a timeout auto-pause filesystem-only (cold-boots on resume; cannot be combined with ``auto_resume``); ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout`` action is ``"pause"``). Example: ``{"on_timeout": {"action": "pause", "keep_memory": False}}``
:param volume_mounts: Dictionary mapping mount paths to AsyncVolume instances or volume names
+ :param logger: Logger used for request and response logging for this sandbox. Accepts any standard library `logging.Logger`. When omitted, no request/response logging is emitted.
:return: A Sandbox instance for the new sandbox
@@ -229,6 +234,7 @@ class AsyncSandbox(SandboxApi):
network=network,
lifecycle=lifecycle,
volume_mounts=transformed_mounts,
+ logger=logger,
**opts,
)
@@ -278,6 +284,7 @@ class AsyncSandbox(SandboxApi):
async def connect(
sandbox_id: str,
timeout: Optional[int] = None,
+ logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> "AsyncSandbox":
"""
@@ -289,6 +296,7 @@ class AsyncSandbox(SandboxApi):
:param sandbox_id: Sandbox ID
:param timeout: Timeout for the sandbox in **seconds**
For running sandboxes, the timeout will update only if the new timeout is longer than the existing one.
+ :param logger: Logger used for request and response logging for this sandbox. Accepts any standard library `logging.Logger`. When omitted, no request/response logging is emitted.
:return: A running sandbox instance
@example
@@ -863,6 +871,7 @@ class AsyncSandbox(SandboxApi):
cls,
sandbox_id: str,
timeout: Optional[int] = None,
+ logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> Self:
debug = ConnectionConfig(**opts).debug
@@ -875,6 +884,7 @@ class AsyncSandbox(SandboxApi):
sandbox = await SandboxApi._cls_connect(
sandbox_id=sandbox_id,
timeout=timeout,
+ logger=logger,
**opts,
)
@@ -888,11 +898,12 @@ class AsyncSandbox(SandboxApi):
"E2b-Sandbox-Id": sandbox_id,
"E2b-Sandbox-Port": str(ConnectionConfig.envd_port),
}
- if envd_access_token is not None:
+ if envd_access_token is not None and not isinstance(envd_access_token, Unset):
sandbox_headers["X-Access-Token"] = envd_access_token
connection_config = ConnectionConfig(
extra_sandbox_headers=sandbox_headers,
+ logger=logger,
**opts,
)
@@ -918,6 +929,7 @@ class AsyncSandbox(SandboxApi):
network: Optional[SandboxNetworkOpts] = None,
lifecycle: Optional[SandboxLifecycle] = None,
volume_mounts: Optional[list] = None,
+ logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> Self:
extra_sandbox_headers = {}
@@ -941,6 +953,7 @@ class AsyncSandbox(SandboxApi):
network=network,
lifecycle=lifecycle,
volume_mounts=volume_mounts,
+ logger=logger,
**opts,
)
@@ -950,7 +963,9 @@ class AsyncSandbox(SandboxApi):
envd_access_token = response.envd_access_token
traffic_access_token = response.traffic_access_token
- if envd_access_token is not None:
+ if envd_access_token is not None and not isinstance(
+ envd_access_token, Unset
+ ):
extra_sandbox_headers["X-Access-Token"] = envd_access_token
extra_sandbox_headers["E2b-Sandbox-Id"] = sandbox_id
@@ -958,6 +973,7 @@ class AsyncSandbox(SandboxApi):
connection_config = ConnectionConfig(
extra_sandbox_headers=extra_sandbox_headers,
+ logger=logger,
**opts,
)
diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
index 7a47ca171..2c376fc8c 100644
--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
@@ -1,4 +1,5 @@
import datetime
+import logging
from typing import Any, Dict, List, Optional, cast
from packaging.version import Version
@@ -198,9 +199,10 @@ class SandboxApi(SandboxBase):
network: Optional[SandboxNetworkOpts] = None,
lifecycle: Optional[SandboxLifecycle] = None,
volume_mounts: Optional[List[SandboxVolumeMountAPI]] = None,
+ logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> SandboxCreateResponse:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(logger=logger, **opts)
# on_timeout accepts a bare action or {"action", "keep_memory"}; normalize.
# Only the object form carries keep_memory; anything else (a bare action
@@ -450,12 +452,13 @@ class SandboxApi(SandboxBase):
cls,
sandbox_id: str,
timeout: Optional[int] = None,
+ logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> SandboxCreateResponse:
timeout = timeout or SandboxBase.default_sandbox_timeout
# Sandbox is not running, resume it
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(logger=logger, **opts)
api_client = get_api_client(config)
res = await post_sandboxes_sandbox_id_connect.asyncio_detailed(
diff --git a/packages/python-sdk/e2b/sandbox_sync/commands/command.py b/packages/python-sdk/e2b/sandbox_sync/commands/command.py
index 992aaf9f3..971d79293 100644
--- a/packages/python-sdk/e2b/sandbox_sync/commands/command.py
+++ b/packages/python-sdk/e2b/sandbox_sync/commands/command.py
@@ -4,6 +4,7 @@ from typing import Callable, Dict, List, Literal, Optional, Union, overload
import e2b_connect
import httpx
from packaging.version import Version
+from e2b.api import make_logging_event_hooks
from e2b.api.client_sync import get_envd_transport
from e2b.connection_config import (
ConnectionConfig,
@@ -43,6 +44,7 @@ class Commands:
base_url=self._envd_api_url,
transport=transport,
headers=self._connection_config.sandbox_headers,
+ event_hooks=make_logging_event_hooks(self._connection_config.logger),
)
def _create_rpc(self) -> process_connect.ProcessClient:
@@ -54,6 +56,7 @@ class Commands:
pool=transport.pool,
json=True,
headers=self._connection_config.sandbox_headers,
+ logger=self._connection_config.logger,
)
@property
diff --git a/packages/python-sdk/e2b/sandbox_sync/commands/pty.py b/packages/python-sdk/e2b/sandbox_sync/commands/pty.py
index 0bcaa8990..f0de8c0ee 100644
--- a/packages/python-sdk/e2b/sandbox_sync/commands/pty.py
+++ b/packages/python-sdk/e2b/sandbox_sync/commands/pty.py
@@ -5,6 +5,7 @@ import threading
from typing import Dict, Optional
from packaging.version import Version
+from e2b.api import make_logging_event_hooks
from e2b.api.client_sync import get_envd_transport
from e2b.envd.process import process_connect, process_pb2
from e2b.connection_config import (
@@ -42,6 +43,7 @@ class Pty:
base_url=self._envd_api_url,
transport=transport,
headers=self._connection_config.sandbox_headers,
+ event_hooks=make_logging_event_hooks(self._connection_config.logger),
)
def _create_rpc(self) -> process_connect.ProcessClient:
@@ -53,6 +55,7 @@ class Pty:
pool=transport.pool,
json=True,
headers=self._connection_config.sandbox_headers,
+ logger=self._connection_config.logger,
)
@property
diff --git a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
index b652572f7..0b9028ad7 100644
--- a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
@@ -5,6 +5,7 @@ import httpx
from packaging.version import Version
import e2b_connect
+from e2b.api import make_logging_event_hooks
from e2b.api.client_sync import get_envd_transport
from e2b.connection_config import (
KEEPALIVE_PING_HEADER,
@@ -93,6 +94,7 @@ class Filesystem:
base_url=self._envd_api_url,
transport=transport,
headers=self._connection_config.sandbox_headers,
+ event_hooks=make_logging_event_hooks(self._connection_config.logger),
)
def _create_rpc(self) -> filesystem_connect.FilesystemClient:
@@ -104,6 +106,7 @@ class Filesystem:
pool=transport.pool,
json=True,
headers=self._connection_config.sandbox_headers,
+ logger=self._connection_config.logger,
)
@property
diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
index eb41bb6d1..df73f2b08 100644
--- a/packages/python-sdk/e2b/sandbox_sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -9,6 +9,7 @@ import httpx
from packaging.version import Version
from typing_extensions import Self, Unpack
+from e2b.api.client.types import Unset
from e2b.connection_config import ApiParams, ConnectionConfig
from e2b.envd.api import ENVD_API_HEALTH_ROUTE, handle_envd_api_exception
from e2b.envd.versions import ENVD_DEBUG_FALLBACK
@@ -169,6 +170,7 @@ class Sandbox(SandboxApi):
network: Optional[SandboxNetworkOpts] = None,
lifecycle: Optional[SandboxLifecycle] = None,
volume_mounts: Optional[SandboxVolumeMount] = None,
+ logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> Self:
"""
@@ -186,6 +188,7 @@ class Sandbox(SandboxApi):
:param network: Sandbox network configuration. ``allow_out``/``deny_out`` may also be a callable receiving a :class:`SandboxNetworkSelectorContext` (``ctx.all_traffic``, ``ctx.rules``) and returning a list of strings. Per-host transform rules are nested under ``network.rules``.
:param lifecycle: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``, or an object ``{"action": "pause"|"kill", "keep_memory": bool}`` where ``keep_memory`` (default ``True``) set to ``False`` makes a timeout auto-pause filesystem-only (cold-boots on resume; cannot be combined with ``auto_resume``); ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout`` action is ``"pause"``). Example: ``{"on_timeout": {"action": "pause", "keep_memory": False}}``
:param volume_mounts: Dictionary mapping mount paths to Volume instances or volume names
+ :param logger: Logger used for request and response logging for this sandbox. Accepts any standard library `logging.Logger`. When omitted, no request/response logging is emitted.
:return: A Sandbox instance for the new sandbox
@@ -217,6 +220,7 @@ class Sandbox(SandboxApi):
network=network,
lifecycle=lifecycle,
volume_mounts=transformed_mounts,
+ logger=logger,
**opts,
)
@@ -267,6 +271,7 @@ class Sandbox(SandboxApi):
def connect(
sandbox_id: str,
timeout: Optional[int] = None,
+ logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> "Sandbox":
"""
@@ -278,6 +283,7 @@ class Sandbox(SandboxApi):
:param sandbox_id: Sandbox ID
:param timeout: Timeout for the sandbox in **seconds**.
For running sandboxes, the timeout will update only if the new timeout is longer than the existing one.
+ :param logger: Logger used for request and response logging for this sandbox. Accepts any standard library `logging.Logger`. When omitted, no request/response logging is emitted.
:return: A running sandbox instance
@example
@@ -853,6 +859,7 @@ class Sandbox(SandboxApi):
cls,
sandbox_id: str,
timeout: Optional[int] = None,
+ logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> Self:
debug = ConnectionConfig(**opts).debug
@@ -865,6 +872,7 @@ class Sandbox(SandboxApi):
sandbox = SandboxApi._cls_connect(
sandbox_id=sandbox_id,
timeout=timeout,
+ logger=logger,
**opts,
)
@@ -878,11 +886,12 @@ class Sandbox(SandboxApi):
"E2b-Sandbox-Id": sandbox_id,
"E2b-Sandbox-Port": str(ConnectionConfig.envd_port),
}
- if envd_access_token is not None:
+ if envd_access_token is not None and not isinstance(envd_access_token, Unset):
sandbox_headers["X-Access-Token"] = envd_access_token
connection_config = ConnectionConfig(
extra_sandbox_headers=sandbox_headers,
+ logger=logger,
**opts,
)
@@ -908,6 +917,7 @@ class Sandbox(SandboxApi):
network: Optional[SandboxNetworkOpts] = None,
lifecycle: Optional[SandboxLifecycle] = None,
volume_mounts: Optional[list] = None,
+ logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> Self:
extra_sandbox_headers = {}
@@ -931,6 +941,7 @@ class Sandbox(SandboxApi):
network=network,
lifecycle=lifecycle,
volume_mounts=volume_mounts,
+ logger=logger,
**opts,
)
@@ -940,7 +951,9 @@ class Sandbox(SandboxApi):
envd_access_token = response.envd_access_token
traffic_access_token = response.traffic_access_token
- if envd_access_token is not None:
+ if envd_access_token is not None and not isinstance(
+ envd_access_token, Unset
+ ):
extra_sandbox_headers["X-Access-Token"] = envd_access_token
extra_sandbox_headers["E2b-Sandbox-Id"] = sandbox_id
@@ -948,6 +961,7 @@ class Sandbox(SandboxApi):
connection_config = ConnectionConfig(
extra_sandbox_headers=extra_sandbox_headers,
+ logger=logger,
**opts,
)
diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
index 3ed10c5f6..6a3b93bbc 100644
--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
@@ -1,4 +1,5 @@
import datetime
+import logging
from typing import Any, Dict, List, Optional, cast
from packaging.version import Version
@@ -197,9 +198,10 @@ class SandboxApi(SandboxBase):
network: Optional[SandboxNetworkOpts] = None,
lifecycle: Optional[SandboxLifecycle] = None,
volume_mounts: Optional[List[SandboxVolumeMountAPI]] = None,
+ logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> SandboxCreateResponse:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(logger=logger, **opts)
# on_timeout accepts a bare action or {"action", "keep_memory"}; normalize.
# Only the object form carries keep_memory; anything else (a bare action
@@ -352,11 +354,12 @@ class SandboxApi(SandboxBase):
cls,
sandbox_id: str,
timeout: Optional[int] = None,
+ logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> SandboxCreateResponse:
timeout = timeout or SandboxBase.default_sandbox_timeout
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(logger=logger, **opts)
api_client = get_api_client(config)
res = post_sandboxes_sandbox_id_connect.sync_detailed(
diff --git a/packages/python-sdk/e2b/volume/client_async/__init__.py b/packages/python-sdk/e2b/volume/client_async/__init__.py
index c5d0f1d36..0df74903c 100644
--- a/packages/python-sdk/e2b/volume/client_async/__init__.py
+++ b/packages/python-sdk/e2b/volume/client_async/__init__.py
@@ -1,5 +1,4 @@
import asyncio
-import logging
import os
import weakref
from typing import Dict, Optional
@@ -8,13 +7,12 @@ import httpx
from httpx import Limits
from httpx._types import ProxyTypes
+from e2b.api import make_async_logging_event_hooks
from e2b.api.metadata import default_headers
from e2b.exceptions import AuthenticationException
from e2b.volume.client.client import AuthenticatedClient as AsyncVolumeApiClient
from e2b.volume.connection_config import VolumeConnectionConfig
-logger = logging.getLogger(__name__)
-
limits = Limits(
max_keepalive_connections=int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS", "20")),
max_connections=int(os.getenv("E2B_MAX_CONNECTIONS", "2000")),
@@ -48,7 +46,11 @@ def get_api_client(config: VolumeConnectionConfig, **kwargs) -> AsyncVolumeApiCl
timeout=(
httpx.Timeout(request_timeout) if request_timeout is not None else None
),
- httpx_args={"proxy": config.proxy, "transport": get_transport(config)},
+ httpx_args={
+ "proxy": config.proxy,
+ "transport": get_transport(config),
+ "event_hooks": make_async_logging_event_hooks(config.logger),
+ },
**kwargs,
)
@@ -62,13 +64,6 @@ class AsyncTransportWithLogger(httpx.AsyncHTTPTransport):
Dict[TransportKey, "AsyncTransportWithLogger"],
] = weakref.WeakKeyDictionary()
- async def handle_async_request(self, request):
- url = f"{request.url.scheme}://{request.url.host}{request.url.path}"
- logger.info(f"Request: {request.method} {url}")
- response = await super().handle_async_request(request)
- logger.info(f"Response: {response.status_code} {url}")
- return response
-
@property
def pool(self):
return self._pool
diff --git a/packages/python-sdk/e2b/volume/client_sync/__init__.py b/packages/python-sdk/e2b/volume/client_sync/__init__.py
index 8659f7083..4ceceda32 100644
--- a/packages/python-sdk/e2b/volume/client_sync/__init__.py
+++ b/packages/python-sdk/e2b/volume/client_sync/__init__.py
@@ -1,4 +1,3 @@
-import logging
import os
import threading
from typing import Dict, Optional
@@ -7,13 +6,12 @@ import httpx
from httpx import Limits
from httpx._types import ProxyTypes
+from e2b.api import make_logging_event_hooks
from e2b.api.metadata import default_headers
from e2b.exceptions import AuthenticationException
from e2b.volume.client.client import AuthenticatedClient as VolumeApiClient
from e2b.volume.connection_config import VolumeConnectionConfig
-logger = logging.getLogger(__name__)
-
limits = Limits(
max_keepalive_connections=int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS", "20")),
max_connections=int(os.getenv("E2B_MAX_CONNECTIONS", "2000")),
@@ -47,7 +45,11 @@ def get_api_client(config: VolumeConnectionConfig, **kwargs) -> VolumeApiClient:
timeout=(
httpx.Timeout(request_timeout) if request_timeout is not None else None
),
- httpx_args={"proxy": config.proxy, "transport": get_transport(config)},
+ httpx_args={
+ "proxy": config.proxy,
+ "transport": get_transport(config),
+ "event_hooks": make_logging_event_hooks(config.logger),
+ },
**kwargs,
)
@@ -55,13 +57,6 @@ def get_api_client(config: VolumeConnectionConfig, **kwargs) -> VolumeApiClient:
class TransportWithLogger(httpx.HTTPTransport):
_thread_local = threading.local()
- def handle_request(self, request):
- url = f"{request.url.scheme}://{request.url.host}{request.url.path}"
- logger.info(f"Request: {request.method} {url}")
- response = super().handle_request(request)
- logger.info(f"Response: {response.status_code} {url}")
- return response
-
@property
def pool(self):
return self._pool
diff --git a/packages/python-sdk/e2b/volume/connection_config.py b/packages/python-sdk/e2b/volume/connection_config.py
index a0f27ec73..266260400 100644
--- a/packages/python-sdk/e2b/volume/connection_config.py
+++ b/packages/python-sdk/e2b/volume/connection_config.py
@@ -1,3 +1,4 @@
+import logging
import os
from typing import Dict, Optional, TypedDict
@@ -41,6 +42,9 @@ class VolumeApiParams(TypedDict, total=False):
proxy: Optional[ProxyTypes]
"""Proxy to use for the request."""
+ logger: Optional[logging.Logger]
+ """Logger used for request and response logging. Accepts a standard library `logging.Logger`."""
+
class VolumeConnectionConfig:
"""
@@ -82,7 +86,9 @@ class VolumeConnectionConfig:
request_timeout: Optional[float] = None,
headers: Optional[Dict[str, str]] = None,
proxy: Optional[ProxyTypes] = None,
+ logger: Optional[logging.Logger] = None,
):
+ self.logger = logger
self.domain = domain or self._domain()
self.debug = debug if debug is not None else self._debug()
@@ -119,6 +125,7 @@ class VolumeConnectionConfig:
token = opts.get("token")
api_url = opts.get("api_url")
proxy = opts.get("proxy")
+ logger = opts.get("logger")
req_headers = self.headers.copy()
if headers is not None:
@@ -133,5 +140,6 @@ class VolumeConnectionConfig:
request_timeout=self.get_request_timeout(request_timeout),
headers=req_headers,
proxy=proxy if proxy is not None else self.proxy,
+ logger=logger if logger is not None else self.logger,
)
)
diff --git a/packages/python-sdk/e2b/volume/volume_async.py b/packages/python-sdk/e2b/volume/volume_async.py
index 3ced6a63e..2e0d711ba 100644
--- a/packages/python-sdk/e2b/volume/volume_async.py
+++ b/packages/python-sdk/e2b/volume/volume_async.py
@@ -91,6 +91,7 @@ class AsyncVolume:
api_url=opts.get("api_url"),
request_timeout=opts.get("request_timeout"),
headers=opts.get("headers"),
+ logger=opts.get("logger"),
proxy=opts.get("proxy") if opts.get("proxy") is not None else self._proxy,
)
diff --git a/packages/python-sdk/e2b/volume/volume_sync.py b/packages/python-sdk/e2b/volume/volume_sync.py
index 8bcf22185..9017526de 100644
--- a/packages/python-sdk/e2b/volume/volume_sync.py
+++ b/packages/python-sdk/e2b/volume/volume_sync.py
@@ -92,6 +92,7 @@ class Volume:
api_url=opts.get("api_url"),
request_timeout=opts.get("request_timeout"),
headers=opts.get("headers"),
+ logger=opts.get("logger"),
proxy=opts.get("proxy") if opts.get("proxy") is not None else self._proxy,
)
diff --git a/packages/python-sdk/e2b_connect/client.py b/packages/python-sdk/e2b_connect/client.py
index 5066f454d..83d006bcb 100644
--- a/packages/python-sdk/e2b_connect/client.py
+++ b/packages/python-sdk/e2b_connect/client.py
@@ -1,6 +1,7 @@
import gzip
import inspect
import json
+import logging
import struct
import typing
@@ -188,6 +189,7 @@ class Client:
compressor=None,
json: Optional[bool] = False,
headers: Optional[Dict[str, str]] = None,
+ logger: Optional[logging.Logger] = None,
):
if headers is None:
headers = {}
@@ -200,6 +202,23 @@ class Client:
self._compressor = compressor
self._headers = headers
self._connection_retries = 3
+ self._logger = logger
+
+ def _log_request(self) -> None:
+ if self._logger is not None:
+ self._logger.info(f"Request: POST {self.url}")
+
+ def _log_response(self, status: int) -> None:
+ if self._logger is None:
+ return
+ if status >= 400:
+ self._logger.error(f"Response: {status} {self.url}")
+ else:
+ self._logger.info(f"Response: {status} {self.url}")
+
+ def _log_stream_message(self) -> None:
+ if self._logger is not None:
+ self._logger.debug(f"Response stream: {self.url}")
def _prepare_unary_request(
self,
@@ -250,6 +269,8 @@ class Client:
self,
http_resp: Response,
):
+ self._log_response(http_resp.status)
+
if http_resp.status != 200:
raise error_for_response(http_resp)
@@ -281,6 +302,7 @@ class Client:
**opts,
)
+ self._log_request()
res = await self.async_pool.request(**req_data)
return self._process_unary_response(res)
@@ -302,6 +324,7 @@ class Client:
**opts,
)
+ self._log_request()
res = self.pool.request(**req_data)
return self._process_unary_response(res)
@@ -390,13 +413,16 @@ class Client:
response_type=self._response_type,
)
+ self._log_request()
async with self.async_pool.stream(**req_data) as http_resp:
if http_resp.status != 200:
+ self._log_response(http_resp.status)
await http_resp.aread()
raise error_for_response(http_resp)
async for chunk in http_resp.aiter_stream():
for parsed in parser.parse(chunk):
+ self._log_stream_message()
yield parsed
def call_server_stream(
@@ -423,13 +449,16 @@ class Client:
response_type=self._response_type,
)
+ self._log_request()
with self.pool.stream(**req_data) as http_resp:
if http_resp.status != 200:
+ self._log_response(http_resp.status)
http_resp.read()
raise error_for_response(http_resp)
for chunk in http_resp.iter_stream():
for parsed in parser.parse(chunk):
+ self._log_stream_message()
yield parsed
def call_client_stream(self, req, **opts):
diff --git a/packages/python-sdk/tests/test_logging_option.py b/packages/python-sdk/tests/test_logging_option.py
new file mode 100644
index 000000000..dcc39d0ca
--- /dev/null
+++ b/packages/python-sdk/tests/test_logging_option.py
@@ -0,0 +1,153 @@
+import inspect
+import logging
+
+import e2b_connect as connect
+from e2b import AsyncSandbox, ConnectionConfig, Sandbox
+from e2b.api import (
+ ApiClient,
+ make_async_logging_event_hooks,
+ make_logging_event_hooks,
+)
+from e2b.connection_config import ApiParams
+from e2b.volume.connection_config import VolumeConnectionConfig
+
+
+def test_connection_config_stores_logger():
+ custom = logging.getLogger("test.custom")
+ config = ConnectionConfig(api_key="e2b_" + "0" * 40, logger=custom)
+ assert config.logger is custom
+
+
+def test_connection_config_logger_defaults_to_none():
+ config = ConnectionConfig(api_key="e2b_" + "0" * 40)
+ assert config.logger is None
+
+
+def test_logger_is_not_a_public_per_request_api_param():
+ # Matching the JS SDK, `logger` is a construction-time option (Sandbox.create
+ # / connect), not a public per-request ApiParams field that control-plane
+ # methods like kill/list/get_info accept from the caller.
+ assert "logger" not in ApiParams.__annotations__
+
+
+def test_get_api_params_propagates_stored_logger():
+ # Instance control-plane methods (kill, pause, set_timeout, get_info,
+ # connect) rebuild a throwaway ConnectionConfig from these params, so the
+ # logger the sandbox was created/connected with must survive the round-trip.
+ custom = logging.getLogger("test.propagate")
+ config = ConnectionConfig(api_key="e2b_" + "0" * 40, logger=custom)
+ assert config.get_api_params()["logger"] is custom
+ assert ConnectionConfig(**config.get_api_params()).logger is custom
+
+ no_logger = ConnectionConfig(api_key="e2b_" + "0" * 40)
+ assert no_logger.get_api_params()["logger"] is None
+
+
+def test_logger_is_accepted_on_create_and_connect():
+ for cls in (Sandbox, AsyncSandbox):
+ assert "logger" in inspect.signature(cls.create).parameters
+ # `logger` is a construction option, so it is accepted by the static
+ # `Sandbox.connect(sandbox_id, ...)` form (which builds a fresh instance)
+ # but not by instance `sandbox.connect()`, where the already-built clients
+ # cannot adopt a new logger.
+ assert "logger" not in inspect.signature(Sandbox.connect).parameters
+ assert "logger" not in inspect.signature(AsyncSandbox.connect).parameters
+
+
+def test_volume_connection_config_stores_and_round_trips_logger():
+ custom = logging.getLogger("test.volume")
+ config = VolumeConnectionConfig(token="token", logger=custom)
+ assert config.logger is custom
+ assert config.get_api_params()["logger"] is custom
+
+
+def test_api_client_uses_config_logger():
+ custom = logging.getLogger("test.api-client")
+ config = ConnectionConfig(api_key="e2b_" + "0" * 40, logger=custom)
+ client = ApiClient(config)
+ try:
+ assert client._logger is custom
+ finally:
+ client.get_httpx_client().close()
+
+
+def test_api_client_without_logger_emits_no_hooks():
+ # With no logger supplied, nothing should be logged (matching the JS SDK,
+ # which only attaches its logging middleware when a logger is given).
+ config = ConnectionConfig(api_key="e2b_" + "0" * 40)
+ client = ApiClient(config)
+ try:
+ assert client._logger is None
+ assert client.get_httpx_client().event_hooks == {
+ "request": [],
+ "response": [],
+ }
+ finally:
+ client.get_httpx_client().close()
+
+
+def test_rpc_client_without_logger_does_not_log(caplog):
+ client = connect.Client(url="https://example.com", response_type=object)
+ assert client._logger is None
+ # The guarded helpers must be safe no-ops when no logger was supplied.
+ with caplog.at_level(logging.DEBUG):
+ client._log_request()
+ client._log_response(200)
+ client._log_response(500)
+ client._log_stream_message()
+ assert caplog.records == []
+
+
+def test_rpc_client_uses_provided_logger(caplog):
+ custom = logging.getLogger("test.rpc")
+ client = connect.Client(
+ url="https://example.com", response_type=object, logger=custom
+ )
+ assert client._logger is custom
+
+ with caplog.at_level(logging.DEBUG, logger="test.rpc"):
+ client._log_request()
+ client._log_response(200)
+ client._log_response(500)
+ client._log_stream_message()
+
+ levels = [(r.levelno, r.getMessage()) for r in caplog.records]
+ assert (logging.INFO, "Request: POST https://example.com") in levels
+ assert (logging.INFO, "Response: 200 https://example.com") in levels
+ assert (logging.ERROR, "Response: 500 https://example.com") in levels
+ assert (logging.DEBUG, "Response stream: https://example.com") in levels
+
+
+def test_logging_event_hooks_without_logger_are_empty():
+ assert make_logging_event_hooks(None) == {}
+ assert make_async_logging_event_hooks(None) == {}
+
+
+def test_sync_logging_event_hooks_emit_records(caplog):
+ log = logging.getLogger("test.hooks.sync")
+ hooks = make_logging_event_hooks(log)
+
+ class _Req:
+ method = "GET"
+ url = "https://example.com/foo"
+
+ class _Resp:
+ def __init__(self, status_code):
+ self.status_code = status_code
+
+ with caplog.at_level(logging.DEBUG, logger="test.hooks.sync"):
+ hooks["request"][0](_Req())
+ hooks["response"][0](_Resp(200))
+ hooks["response"][0](_Resp(500))
+
+ levels = [(r.levelno, r.getMessage()) for r in caplog.records]
+ assert (logging.INFO, "Request GET https://example.com/foo") in levels
+ assert (logging.INFO, "Response 200") in levels
+ assert (logging.ERROR, "Response 500") in levels
+
+
+def test_make_async_logging_event_hooks_shape():
+ hooks = make_async_logging_event_hooks(logging.getLogger("test.hooks.async"))
+ assert set(hooks) == {"request", "response"}
+ assert len(hooks["request"]) == 1
+ assert len(hooks["response"]) == 1