Skip to content

Commit 2261661

Browse files
Replace traceback.print_exc() with logger.exception() for proper logging (#160)
Using traceback.print_exc() and traceback.print_exception() writes directly to stderr, bypassing the Python logging system. This prevents users from: - Configuring log destinations (files, syslog, cloud services) - Controlling log levels and filtering - Using structured logging formats (JSON, etc.) - Integrating with monitoring and alerting systems PEP 337 explicitly recommends: "Replace traceback.print_exception with _log.exception" and states that modules should "use the logging system instead of print or sys.stdout.write." Changes: - Added logging.getLogger(__name__) to server.py and server_context.py - Replaced traceback.print_exc() with logger.exception() in 2 locations - Replaced traceback.print_exception() with logger.exception() in 2 locations This allows applications using the SDK to properly control exception logging through standard Python logging configuration. References: - PEP 337: https://peps.python.org/pep-0337/ - Python Logging HOWTO: https://docs.python.org/3/howto/logging.html
1 parent 292a6ef commit 2261661

File tree

2 files changed

+9
-7
lines changed

2 files changed

+9
-7
lines changed

python/restate/server.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
"""This module contains the ASGI server for the restate framework."""
1212

1313
import asyncio
14+
import logging
1415
from typing import Dict, TypedDict, Literal
15-
import traceback
1616

1717
from restate.discovery import compute_discovery_json
1818
from restate.endpoint import Endpoint
@@ -24,6 +24,8 @@
2424
from restate._internal import PyIdentityVerifier, IdentityVerificationException # pylint: disable=import-error,no-name-in-module
2525
from restate._internal import SDK_VERSION # pylint: disable=import-error,no-name-in-module
2626

27+
logger = logging.getLogger(__name__)
28+
2729
X_RESTATE_SERVER = header_to_binary([("x-restate-server", f"restate-sdk-python/{SDK_VERSION}")])
2830

2931

@@ -165,7 +167,7 @@ async def process_invocation_to_completion(
165167
return
166168
# pylint: disable=W0718
167169
except Exception:
168-
traceback.print_exc()
170+
logger.exception("Exception in Restate handler")
169171
try:
170172
await context.leave()
171173
finally:
@@ -272,7 +274,7 @@ async def app(scope: Scope, receive: Receive, send: Send):
272274
except LifeSpanNotImplemented as e:
273275
raise e
274276
except Exception as e:
275-
traceback.print_exc()
277+
logger.exception("Exception in ASGI app")
276278
raise e
277279

278280
if is_running_on_lambda():

python/restate/server_context.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from datetime import timedelta
2525
import inspect
2626
import functools
27+
import logging
2728
from typing import Any, Awaitable, Callable, Dict, List, Optional, TypeVar, Union, Coroutine
2829
import typing
2930
import traceback
@@ -59,6 +60,7 @@
5960
DoWaitPendingRun,
6061
)
6162

63+
logger = logging.getLogger(__name__)
6264

6365
T = TypeVar("T")
6466
I = TypeVar("I")
@@ -448,8 +450,7 @@ async def must_take_notification(self, handle):
448450
if isinstance(res, Exception):
449451
# We might need to write out something at this point.
450452
await self.take_and_send_output()
451-
# Print this exception, might be relevant for the user
452-
traceback.print_exception(res)
453+
logger.exception("Exception in take_notification", exc_info=res)
453454
raise SdkInternalException() from res
454455
if isinstance(res, Suspended):
455456
# We might need to write out something at this point.
@@ -469,8 +470,7 @@ async def create_poll_or_cancel_coroutine(self, handles: typing.List[int]) -> No
469470
await self.take_and_send_output()
470471
do_progress_response = self.vm.do_progress(handles)
471472
if isinstance(do_progress_response, BaseException):
472-
# Print this exception, might be relevant for the user
473-
traceback.print_exception(do_progress_response)
473+
logger.exception("Exception in do_progress", exc_info=do_progress_response)
474474
raise SdkInternalException() from do_progress_response
475475
if isinstance(do_progress_response, Suspended):
476476
raise SuspendedException()

0 commit comments

Comments
 (0)