From 250e40d84d33ce276381973bb9d75723cf035a6a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 15:51:44 +0000 Subject: [PATCH 1/3] feat: redirect run logs in `TaskClient.call` `TaskClient.call` accepts the same `logger` argument as `ActorClient.call` and redirects the run's log and status messages to it while waiting for the run to finish. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAL9oK2rVWgWZKeeVVg --- docs/02_concepts/06_logging.mdx | 2 +- src/apify_client/_resource_clients/task.py | 45 ++++++++++++++++++-- tests/unit/test_call_poll_timeout.py | 6 +-- tests/unit/test_logging.py | 48 ++++++++++++++++++++++ tests/unit/test_task_start_params.py | 2 +- tests/unit/test_wait_for_resources.py | 4 +- 6 files changed, 97 insertions(+), 10 deletions(-) diff --git a/docs/02_concepts/06_logging.mdx b/docs/02_concepts/06_logging.mdx index 5acf3f8e..acc20232 100644 --- a/docs/02_concepts/06_logging.mdx +++ b/docs/02_concepts/06_logging.mdx @@ -41,7 +41,7 @@ For more information on creating and using custom log formatters, refer to the o ## Redirecting Actor run logs -When you start an Actor with `ActorClient.call`, the client redirects the run's log to a Python logger while it waits for the run to finish. The same logger also receives the run's status and status message whenever they change. The `logger` argument controls where the lines go: +When you start an Actor with `ActorClient.call` or a task with `TaskClient.call`, the client redirects the run's log to a Python logger while it waits for the run to finish. The same logger also receives the run's status and status message whenever they change. The `logger` argument controls where the lines go: - `'default'` (the default) - A built-in redirect logger named after the Actor and the run ID. - A `logging.Logger` - Your own logger receives the lines, so give it a handler and a level that let them through. diff --git a/src/apify_client/_resource_clients/task.py b/src/apify_client/_resource_clients/task.py index 3f87d0ff..b8c357eb 100644 --- a/src/apify_client/_resource_clients/task.py +++ b/src/apify_client/_resource_clients/task.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Literal from apify_client._docs import docs_group from apify_client._models import ( @@ -23,6 +23,7 @@ if TYPE_CHECKING: from datetime import timedelta from decimal import Decimal + from logging import Logger from apify_client._literals import ActorJobStatus, RunOrigin from apify_client._resource_clients import ( @@ -336,6 +337,7 @@ def call( webhooks: WebhooksList | None = None, wait_duration: timedelta | None = None, wait_for_resources: bool | timedelta = False, + logger: Logger | Literal['default'] | None = 'default', timeout: Timeout = 'no_timeout', ) -> Run | None: """Start a task and wait for it to finish before returning the Run object. @@ -370,6 +372,10 @@ def call( than the whole memory limit of the account is rejected with `actor-memory-limit-exceeded` as well and never starts, so `True` retries it forever. The time spent retrying doesn't count toward `wait_duration`. + logger: Logger used to redirect logs from the Actor run. Using "default" literal means that a predefined + default logger will be used. Setting `None` will disable any log propagation. Passing custom logger + will redirect logs to the provided logger. The logger is also used to capture status and status message + of the other Actor run. timeout: Timeout for each API HTTP request, both the start and every poll. The server holds each poll for up to 60 seconds, so a shorter timeout cuts healthy polls off. Each retry doubles the timeout, and the call fails if the retries run out first. @@ -397,7 +403,21 @@ def call( http_client=self._http_client, client_registry=self._client_registry, ) - return run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + + if not logger: + return run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + + if logger == 'default': + logger = None + + # With the default logger, each helper rebuilds the same redirect logger from scratch, so both must exist before + # either starts polling; otherwise the streamed log reconfigures a logger the status watcher thread is already + # writing into. + status_redirector = run_client.get_status_message_watcher(to_logger=logger) + streamed_log = run_client.get_streamed_log(to_logger=logger) + + with status_redirector, streamed_log: + return run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) def get_input(self, *, timeout: Timeout = 'short') -> dict: """Retrieve the default input for this task. @@ -775,6 +795,7 @@ async def call( webhooks: WebhooksList | None = None, wait_duration: timedelta | None = None, wait_for_resources: bool | timedelta = False, + logger: Logger | Literal['default'] | None = 'default', timeout: Timeout = 'no_timeout', ) -> Run | None: """Start a task and wait for it to finish before returning the Run object. @@ -809,6 +830,10 @@ async def call( than the whole memory limit of the account is rejected with `actor-memory-limit-exceeded` as well and never starts, so `True` retries it forever. The time spent retrying doesn't count toward `wait_duration`. + logger: Logger used to redirect logs from the Actor run. Using "default" literal means that a predefined + default logger will be used. Setting `None` will disable any log propagation. Passing custom logger + will redirect logs to the provided logger. The logger is also used to capture status and status message + of the other Actor run. timeout: Timeout for each API HTTP request, both the start and every poll. The server holds each poll for up to 60 seconds, so a shorter timeout cuts healthy polls off. Each retry doubles the timeout, and the call fails if the retries run out first. @@ -835,7 +860,21 @@ async def call( http_client=self._http_client, client_registry=self._client_registry, ) - return await run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + + if not logger: + return await run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + + if logger == 'default': + logger = None + + # With the default logger, each helper rebuilds the same redirect logger from scratch, so both must exist before + # either starts polling; otherwise the streamed log reconfigures a logger the status watcher task is already + # writing into. + status_redirector = await run_client.get_status_message_watcher(to_logger=logger) + streamed_log = await run_client.get_streamed_log(to_logger=logger) + + async with status_redirector, streamed_log: + return await run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) async def get_input(self, *, timeout: Timeout = 'short') -> dict: """Retrieve the default input for this task. diff --git a/tests/unit/test_call_poll_timeout.py b/tests/unit/test_call_poll_timeout.py index 04cbc451..3816415f 100644 --- a/tests/unit/test_call_poll_timeout.py +++ b/tests/unit/test_call_poll_timeout.py @@ -19,8 +19,7 @@ def test_call_passes_timeout_to_poll_sync(monkeypatch: pytest.MonkeyPatch, resou monkeypatch.setattr(sub_client._client_registry, 'run_client', Mock(return_value=Mock(wait_for_finish=poll))) timeout = timedelta(seconds=90) - kwargs = {'logger': None} if resource == 'actor' else {} - sub_client.call(timeout=timeout, wait_duration=timedelta(seconds=120), **kwargs) + sub_client.call(timeout=timeout, wait_duration=timedelta(seconds=120), logger=None) assert start.call_args.kwargs['timeout'] == timeout poll.assert_called_once_with(wait_duration=timedelta(seconds=120), timeout=timeout) @@ -37,8 +36,7 @@ async def test_call_passes_timeout_to_poll_async(monkeypatch: pytest.MonkeyPatch monkeypatch.setattr(sub_client._client_registry, 'run_client', Mock(return_value=Mock(wait_for_finish=poll))) timeout = timedelta(seconds=90) - kwargs = {'logger': None} if resource == 'actor' else {} - await sub_client.call(timeout=timeout, wait_duration=timedelta(seconds=120), **kwargs) + await sub_client.call(timeout=timeout, wait_duration=timedelta(seconds=120), logger=None) assert start.call_args.kwargs['timeout'] == timeout poll.assert_awaited_once_with(wait_duration=timedelta(seconds=120), timeout=timeout) diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py index 9d360b04..39a861f6 100644 --- a/tests/unit/test_logging.py +++ b/tests/unit/test_logging.py @@ -36,6 +36,7 @@ _MOCKED_RUN_ID = 'mocked_run_id' _MOCKED_ACTOR_NAME = 'mocked_actor_name' _MOCKED_ACTOR_ID = 'mocked_actor_id' +_MOCKED_TASK_ID = 'mocked_task_id' _MOCKED_ACTOR_LOGS = ( # Several logs merged into one chunk ( @@ -225,6 +226,13 @@ def mock_api(httpserver: HTTPServer) -> None: } ) + # Add task run creation endpoint + httpserver.expect_request(f'/v2/actor-tasks/{_MOCKED_TASK_ID}/runs', method='POST').respond_with_json( + { + 'data': status_generator._create_minimal_run_data('Initial message', 'RUNNING', is_terminal=False), + } + ) + httpserver.expect_request( f'/v2/actor-runs/{_MOCKED_RUN_ID}/log', method='GET', query_string='stream=true&raw=true' ).respond_with_handler(_streaming_log_handler) @@ -515,6 +523,46 @@ def test_actor_call_redirect_logs_to_custom_logger_sync( ) +@pytest.mark.usefixtures('mock_api', 'propagate_stream_logs', 'reduce_final_timeout_for_status_message_redirector') +async def test_task_call_redirect_logs_to_custom_logger_async( + caplog: LogCaptureFixture, + httpserver: HTTPServer, +) -> None: + """Test that task call logs are redirected correctly to the custom logger.""" + api_url = httpserver.url_for('/').removesuffix('/') + + logger_name = 'custom_logger' + logger = logging.getLogger(logger_name) + task_client = ApifyClientAsync(token='mocked_token', api_url=api_url).task(task_id=_MOCKED_TASK_ID) + + with caplog.at_level(logging.DEBUG, logger=logger_name): + await task_client.call(logger=logger) + + assert {(record.message, record.levelno) for record in caplog.records} == set( + _EXPECTED_MESSAGES_AND_LEVELS_WITH_STATUS_MESSAGES + ) + + +@pytest.mark.usefixtures('mock_api', 'propagate_stream_logs', 'reduce_final_timeout_for_status_message_redirector') +def test_task_call_redirect_logs_to_custom_logger_sync( + caplog: LogCaptureFixture, + httpserver: HTTPServer, +) -> None: + """Test that task call logs are redirected correctly to the custom logger.""" + api_url = httpserver.url_for('/').removesuffix('/') + + logger_name = 'custom_logger' + logger = logging.getLogger(logger_name) + task_client = ApifyClient(token='mocked_token', api_url=api_url).task(task_id=_MOCKED_TASK_ID) + + with caplog.at_level(logging.DEBUG, logger=logger_name): + task_client.call(logger=logger) + + assert {(record.message, record.levelno) for record in caplog.records} == set( + _EXPECTED_MESSAGES_AND_LEVELS_WITH_STATUS_MESSAGES + ) + + @pytest.mark.usefixtures('mock_api', 'propagate_stream_logs', 'reduce_final_timeout_for_status_message_redirector') async def test_redirect_status_message_async( *, diff --git a/tests/unit/test_task_start_params.py b/tests/unit/test_task_start_params.py index 4485db26..2c198838 100644 --- a/tests/unit/test_task_start_params.py +++ b/tests/unit/test_task_start_params.py @@ -35,7 +35,7 @@ STARTERS = [ pytest.param(lambda c, **kw: c.task('task-id').start(**kw), id='start'), - pytest.param(lambda c, **kw: c.task('task-id').call(**kw), id='call'), + pytest.param(lambda c, **kw: c.task('task-id').call(logger=None, **kw), id='call'), ] diff --git a/tests/unit/test_wait_for_resources.py b/tests/unit/test_wait_for_resources.py index d3aa0050..9aa7eef9 100644 --- a/tests/unit/test_wait_for_resources.py +++ b/tests/unit/test_wait_for_resources.py @@ -65,7 +65,9 @@ def start_actor(client: ApifyClient | ApifyClientAsync, **kwargs: Any) -> Any: lambda c, **kw: c.actor('actor-id').call(logger=None, **kw), '/v2/actors/actor-id/runs', id='actor call' ), pytest.param(lambda c, **kw: c.task('task-id').start(**kw), '/v2/actor-tasks/task-id/runs', id='task start'), - pytest.param(lambda c, **kw: c.task('task-id').call(**kw), '/v2/actor-tasks/task-id/runs', id='task call'), + pytest.param( + lambda c, **kw: c.task('task-id').call(logger=None, **kw), '/v2/actor-tasks/task-id/runs', id='task call' + ), ] From e7ca391e339e11250b038d27798229dc1f85b0bc Mon Sep 17 00:00:00 2001 From: Josef Prochazka Date: Wed, 25 Nov 2026 09:14:12 +0100 Subject: [PATCH 2/3] Re-use through private method --- src/apify_client/_resource_clients/actor.py | 30 +----------- src/apify_client/_resource_clients/run.py | 52 ++++++++++++++++++++- src/apify_client/_resource_clients/task.py | 30 +----------- tests/unit/test_call_poll_timeout.py | 19 ++++---- 4 files changed, 64 insertions(+), 67 deletions(-) diff --git a/src/apify_client/_resource_clients/actor.py b/src/apify_client/_resource_clients/actor.py index eb7cec5d..6babb2c3 100644 --- a/src/apify_client/_resource_clients/actor.py +++ b/src/apify_client/_resource_clients/actor.py @@ -459,20 +459,7 @@ def call( client_registry=self._client_registry, ) - if not logger: - return run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) - - if logger == 'default': - logger = None - - # With the default logger, each helper rebuilds the same redirect logger from scratch, so both must exist before - # either starts polling; otherwise the streamed log reconfigures a logger the status watcher thread is already - # writing into. - status_redirector = run_client.get_status_message_watcher(to_logger=logger) - streamed_log = run_client.get_streamed_log(to_logger=logger) - - with status_redirector, streamed_log: - return run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + return run_client._wait_with_logs(logger=logger, wait_duration=wait_duration, timeout=timeout) # noqa: SLF001 def build( self, @@ -1107,20 +1094,7 @@ async def call( client_registry=self._client_registry, ) - if not logger: - return await run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) - - if logger == 'default': - logger = None - - # With the default logger, each helper rebuilds the same redirect logger from scratch, so both must exist before - # either starts polling; otherwise the streamed log reconfigures a logger the status watcher task is already - # writing into. - status_redirector = await run_client.get_status_message_watcher(to_logger=logger) - streamed_log = await run_client.get_streamed_log(to_logger=logger) - - async with status_redirector, streamed_log: - return await run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + return await run_client._wait_with_logs(logger=logger, wait_duration=wait_duration, timeout=timeout) # noqa: SLF001 async def build( self, diff --git a/src/apify_client/_resource_clients/run.py b/src/apify_client/_resource_clients/run.py index 39cbc399..331e0435 100644 --- a/src/apify_client/_resource_clients/run.py +++ b/src/apify_client/_resource_clients/run.py @@ -5,7 +5,7 @@ import string import time from datetime import timedelta -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Literal from apify_client._docs import docs_group from apify_client._logging import create_redirect_logger @@ -482,6 +482,31 @@ def get_status_message_watcher( return StatusMessageWatcher(run_client=self, to_logger=to_logger, check_period=check_period) + def _wait_with_logs( + self, + *, + logger: logging.Logger | Literal['default'] | None, + wait_duration: timedelta | None, + timeout: Timeout, + ) -> Run | None: + """Wait for the run to finish while redirecting its log and status messages to `logger`. + + `'default'` redirects to a logger named after the Actor and run, and `None` waits without any redirection. + """ + if logger is None: + return self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + + to_logger = None if logger == 'default' else logger + + # With the default logger, each helper rebuilds the same redirect logger from scratch, so both must exist before + # either starts polling; otherwise the streamed log reconfigures a logger the status watcher thread is already + # writing into. + status_watcher = self.get_status_message_watcher(to_logger=to_logger) + streamed_log = self.get_streamed_log(to_logger=to_logger) + + with status_watcher, streamed_log: + return self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + def iterate_dataset_items( self, *, @@ -1043,6 +1068,31 @@ async def get_status_message_watcher( return StatusMessageWatcherAsync(run_client=self, to_logger=to_logger, check_period=check_period) + async def _wait_with_logs( + self, + *, + logger: logging.Logger | Literal['default'] | None, + wait_duration: timedelta | None, + timeout: Timeout, + ) -> Run | None: + """Wait for the run to finish while redirecting its log and status messages to `logger`. + + `'default'` redirects to a logger named after the Actor and run, and `None` waits without any redirection. + """ + if logger is None: + return await self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + + to_logger = None if logger == 'default' else logger + + # With the default logger, each helper rebuilds the same redirect logger from scratch, so both must exist before + # either starts polling; otherwise the streamed log reconfigures a logger the status watcher task is already + # writing into. + status_watcher = await self.get_status_message_watcher(to_logger=to_logger) + streamed_log = await self.get_streamed_log(to_logger=to_logger) + + async with status_watcher, streamed_log: + return await self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + async def iterate_dataset_items( self, *, diff --git a/src/apify_client/_resource_clients/task.py b/src/apify_client/_resource_clients/task.py index b8c357eb..66ce6711 100644 --- a/src/apify_client/_resource_clients/task.py +++ b/src/apify_client/_resource_clients/task.py @@ -404,20 +404,7 @@ def call( client_registry=self._client_registry, ) - if not logger: - return run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) - - if logger == 'default': - logger = None - - # With the default logger, each helper rebuilds the same redirect logger from scratch, so both must exist before - # either starts polling; otherwise the streamed log reconfigures a logger the status watcher thread is already - # writing into. - status_redirector = run_client.get_status_message_watcher(to_logger=logger) - streamed_log = run_client.get_streamed_log(to_logger=logger) - - with status_redirector, streamed_log: - return run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + return run_client._wait_with_logs(logger=logger, wait_duration=wait_duration, timeout=timeout) # noqa: SLF001 def get_input(self, *, timeout: Timeout = 'short') -> dict: """Retrieve the default input for this task. @@ -861,20 +848,7 @@ async def call( client_registry=self._client_registry, ) - if not logger: - return await run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) - - if logger == 'default': - logger = None - - # With the default logger, each helper rebuilds the same redirect logger from scratch, so both must exist before - # either starts polling; otherwise the streamed log reconfigures a logger the status watcher task is already - # writing into. - status_redirector = await run_client.get_status_message_watcher(to_logger=logger) - streamed_log = await run_client.get_streamed_log(to_logger=logger) - - async with status_redirector, streamed_log: - return await run_client.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + return await run_client._wait_with_logs(logger=logger, wait_duration=wait_duration, timeout=timeout) # noqa: SLF001 async def get_input(self, *, timeout: Timeout = 'short') -> dict: """Retrieve the default input for this task. diff --git a/tests/unit/test_call_poll_timeout.py b/tests/unit/test_call_poll_timeout.py index 3816415f..d72dfec8 100644 --- a/tests/unit/test_call_poll_timeout.py +++ b/tests/unit/test_call_poll_timeout.py @@ -6,6 +6,7 @@ import pytest from apify_client import ApifyClient, ApifyClientAsync +from apify_client._resource_clients import RunClient, RunClientAsync @pytest.mark.parametrize('resource', [pytest.param('actor', id='actor'), pytest.param('task', id='task')]) @@ -16,7 +17,7 @@ def test_call_passes_timeout_to_poll_sync(monkeypatch: pytest.MonkeyPatch, resou start = Mock(return_value=Mock(id='run-id')) poll = Mock(return_value=Mock(id='run-id')) monkeypatch.setattr(sub_client, 'start', start) - monkeypatch.setattr(sub_client._client_registry, 'run_client', Mock(return_value=Mock(wait_for_finish=poll))) + monkeypatch.setattr(RunClient, 'wait_for_finish', poll) timeout = timedelta(seconds=90) sub_client.call(timeout=timeout, wait_duration=timedelta(seconds=120), logger=None) @@ -33,7 +34,7 @@ async def test_call_passes_timeout_to_poll_async(monkeypatch: pytest.MonkeyPatch start = AsyncMock(return_value=Mock(id='run-id')) poll = AsyncMock(return_value=Mock(id='run-id')) monkeypatch.setattr(sub_client, 'start', start) - monkeypatch.setattr(sub_client._client_registry, 'run_client', Mock(return_value=Mock(wait_for_finish=poll))) + monkeypatch.setattr(RunClientAsync, 'wait_for_finish', poll) timeout = timedelta(seconds=90) await sub_client.call(timeout=timeout, wait_duration=timedelta(seconds=120), logger=None) @@ -47,10 +48,9 @@ def test_actor_call_passes_timeout_to_poll_with_log_redirect(monkeypatch: pytest actor = ApifyClient(token='test_token').actor('actor-id') monkeypatch.setattr(actor, 'start', Mock(return_value=Mock(id='run-id'))) poll = Mock() - run_client = Mock(wait_for_finish=poll) - run_client.get_status_message_watcher.return_value = MagicMock() - run_client.get_streamed_log.return_value = MagicMock() - monkeypatch.setattr(actor._client_registry, 'run_client', Mock(return_value=run_client)) + monkeypatch.setattr(RunClient, 'wait_for_finish', poll) + monkeypatch.setattr(RunClient, 'get_status_message_watcher', Mock(return_value=MagicMock())) + monkeypatch.setattr(RunClient, 'get_streamed_log', Mock(return_value=MagicMock())) timeout = timedelta(seconds=90) actor.call(timeout=timeout) @@ -63,10 +63,9 @@ async def test_actor_call_passes_timeout_to_poll_with_log_redirect_async(monkeyp actor = ApifyClientAsync(token='test_token').actor('actor-id') monkeypatch.setattr(actor, 'start', AsyncMock(return_value=Mock(id='run-id'))) poll = AsyncMock() - run_client = Mock(wait_for_finish=poll) - run_client.get_status_message_watcher = AsyncMock(return_value=MagicMock()) - run_client.get_streamed_log = AsyncMock(return_value=MagicMock()) - monkeypatch.setattr(actor._client_registry, 'run_client', Mock(return_value=run_client)) + monkeypatch.setattr(RunClientAsync, 'wait_for_finish', poll) + monkeypatch.setattr(RunClientAsync, 'get_status_message_watcher', AsyncMock(return_value=MagicMock())) + monkeypatch.setattr(RunClientAsync, 'get_streamed_log', AsyncMock(return_value=MagicMock())) timeout = timedelta(seconds=90) await actor.call(timeout=timeout) From 69f31b14b85a24b53f73ee6b5de7dbb89e87a9e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 10:38:10 +0000 Subject: [PATCH 3/3] fix: wait for the run without log redirection when its setup fails `ActorClient.call` and `TaskClient.call` start the run before they set up log redirection, which reads the run and its Actor. A failure there, for example a token that may run a task but not read its Actor, made `call` raise and lose the started run. It is now logged as a warning and the run is waited for without redirection. Also moves `_wait_with_logs` after the public methods, fixes the task `logger` docstring, and adds task tests for `logger='default'` and `logger=None`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017ocuAHA5qh4VqF6Ps7XR5p --- src/apify_client/_resource_clients/run.py | 117 +++++++++-------- src/apify_client/_resource_clients/task.py | 16 +-- tests/unit/test_logging.py | 141 ++++++++++++++++++++- 3 files changed, 215 insertions(+), 59 deletions(-) diff --git a/src/apify_client/_resource_clients/run.py b/src/apify_client/_resource_clients/run.py index 331e0435..22c44711 100644 --- a/src/apify_client/_resource_clients/run.py +++ b/src/apify_client/_resource_clients/run.py @@ -9,6 +9,7 @@ from apify_client._docs import docs_group from apify_client._logging import create_redirect_logger +from apify_client._logging import logger as library_logger from apify_client._models import Run, RunResponse from apify_client._pagination import DEFAULT_CHUNK_SIZE from apify_client._resource_clients._resource_client import _TERMINAL_STATUSES, ResourceClient, ResourceClientAsync @@ -482,31 +483,6 @@ def get_status_message_watcher( return StatusMessageWatcher(run_client=self, to_logger=to_logger, check_period=check_period) - def _wait_with_logs( - self, - *, - logger: logging.Logger | Literal['default'] | None, - wait_duration: timedelta | None, - timeout: Timeout, - ) -> Run | None: - """Wait for the run to finish while redirecting its log and status messages to `logger`. - - `'default'` redirects to a logger named after the Actor and run, and `None` waits without any redirection. - """ - if logger is None: - return self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) - - to_logger = None if logger == 'default' else logger - - # With the default logger, each helper rebuilds the same redirect logger from scratch, so both must exist before - # either starts polling; otherwise the streamed log reconfigures a logger the status watcher thread is already - # writing into. - status_watcher = self.get_status_message_watcher(to_logger=to_logger) - streamed_log = self.get_streamed_log(to_logger=to_logger) - - with status_watcher, streamed_log: - return self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) - def iterate_dataset_items( self, *, @@ -623,6 +599,39 @@ def list_page(page_offset: int, page_limit: int) -> DatasetItemsPage: if end is not None and position >= end: return + def _wait_with_logs( + self, + *, + logger: logging.Logger | Literal['default'] | None, + wait_duration: timedelta | None, + timeout: Timeout, + ) -> Run | None: + """Wait for the run to finish while redirecting its log and status messages to `logger`. + + `'default'` redirects to a logger named after the Actor and run, and `None` waits without any redirection. A + failure to set up the redirection never fails the wait: the run is then waited for without it. + """ + if logger is None: + return self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + + to_logger = None if logger == 'default' else logger + + try: + # With the default logger, each helper rebuilds the same redirect logger from scratch, so both must exist + # before either starts polling; otherwise the streamed log reconfigures a logger the status watcher thread + # is already writing into. + status_watcher = self.get_status_message_watcher(to_logger=to_logger) + streamed_log = self.get_streamed_log(to_logger=to_logger) + except Exception as exc: + # The run has already started, so the caller must get it even when the redirection cannot be set up. + library_logger.warning( + 'Waiting for run %s without log redirection, which could not be set up: %r', self.resource_id, exc + ) + return self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + + with status_watcher, streamed_log: + return self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + @docs_group('Resource clients') class RunClientAsync(ResourceClientAsync): @@ -1068,31 +1077,6 @@ async def get_status_message_watcher( return StatusMessageWatcherAsync(run_client=self, to_logger=to_logger, check_period=check_period) - async def _wait_with_logs( - self, - *, - logger: logging.Logger | Literal['default'] | None, - wait_duration: timedelta | None, - timeout: Timeout, - ) -> Run | None: - """Wait for the run to finish while redirecting its log and status messages to `logger`. - - `'default'` redirects to a logger named after the Actor and run, and `None` waits without any redirection. - """ - if logger is None: - return await self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) - - to_logger = None if logger == 'default' else logger - - # With the default logger, each helper rebuilds the same redirect logger from scratch, so both must exist before - # either starts polling; otherwise the streamed log reconfigures a logger the status watcher task is already - # writing into. - status_watcher = await self.get_status_message_watcher(to_logger=to_logger) - streamed_log = await self.get_streamed_log(to_logger=to_logger) - - async with status_watcher, streamed_log: - return await self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) - async def iterate_dataset_items( self, *, @@ -1210,3 +1194,36 @@ async def list_page(page_offset: int, page_limit: int) -> DatasetItemsPage: position += page_limit if end is not None and position >= end: return + + async def _wait_with_logs( + self, + *, + logger: logging.Logger | Literal['default'] | None, + wait_duration: timedelta | None, + timeout: Timeout, + ) -> Run | None: + """Wait for the run to finish while redirecting its log and status messages to `logger`. + + `'default'` redirects to a logger named after the Actor and run, and `None` waits without any redirection. A + failure to set up the redirection never fails the wait: the run is then waited for without it. + """ + if logger is None: + return await self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + + to_logger = None if logger == 'default' else logger + + try: + # With the default logger, each helper rebuilds the same redirect logger from scratch, so both must exist + # before either starts polling; otherwise the streamed log reconfigures a logger the status watcher task + # is already writing into. + status_watcher = await self.get_status_message_watcher(to_logger=to_logger) + streamed_log = await self.get_streamed_log(to_logger=to_logger) + except Exception as exc: + # The run has already started, so the caller must get it even when the redirection cannot be set up. + library_logger.warning( + 'Waiting for run %s without log redirection, which could not be set up: %r', self.resource_id, exc + ) + return await self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) + + async with status_watcher, streamed_log: + return await self.wait_for_finish(wait_duration=wait_duration, timeout=timeout) diff --git a/src/apify_client/_resource_clients/task.py b/src/apify_client/_resource_clients/task.py index 66ce6711..d868b320 100644 --- a/src/apify_client/_resource_clients/task.py +++ b/src/apify_client/_resource_clients/task.py @@ -372,10 +372,10 @@ def call( than the whole memory limit of the account is rejected with `actor-memory-limit-exceeded` as well and never starts, so `True` retries it forever. The time spent retrying doesn't count toward `wait_duration`. - logger: Logger used to redirect logs from the Actor run. Using "default" literal means that a predefined - default logger will be used. Setting `None` will disable any log propagation. Passing custom logger - will redirect logs to the provided logger. The logger is also used to capture status and status message - of the other Actor run. + logger: Logger used to redirect logs from the task run. Using the `'default'` literal means that a + predefined default logger will be used. Setting `None` will disable any log propagation. Passing custom + logger will redirect logs to the provided logger. The logger is also used to capture status and status + message of the task run. timeout: Timeout for each API HTTP request, both the start and every poll. The server holds each poll for up to 60 seconds, so a shorter timeout cuts healthy polls off. Each retry doubles the timeout, and the call fails if the retries run out first. @@ -817,10 +817,10 @@ async def call( than the whole memory limit of the account is rejected with `actor-memory-limit-exceeded` as well and never starts, so `True` retries it forever. The time spent retrying doesn't count toward `wait_duration`. - logger: Logger used to redirect logs from the Actor run. Using "default" literal means that a predefined - default logger will be used. Setting `None` will disable any log propagation. Passing custom logger - will redirect logs to the provided logger. The logger is also used to capture status and status message - of the other Actor run. + logger: Logger used to redirect logs from the task run. Using the `'default'` literal means that a + predefined default logger will be used. Setting `None` will disable any log propagation. Passing custom + logger will redirect logs to the provided logger. The logger is also used to capture status and status + message of the task run. timeout: Timeout for each API HTTP request, both the start and every poll. The server holds each poll for up to 60 seconds, so a shorter timeout cuts healthy polls off. Each retry doubles the timeout, and the call fails if the retries run out first. diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py index 39a861f6..da7d23b4 100644 --- a/tests/unit/test_logging.py +++ b/tests/unit/test_logging.py @@ -17,6 +17,8 @@ from apify_client import ApifyClient, ApifyClientAsync from apify_client._logging import LoggerOnce, RedirectLogFormatter +from apify_client._models import Run +from apify_client._resource_clients import RunClient, RunClientAsync from apify_client._resource_clients import run as run_module from apify_client._status_message_watcher import StatusMessageWatcher, StatusMessageWatcherBase from apify_client._streamed_log import StreamedLog, StreamedLogAsync, StreamedLogBase @@ -28,7 +30,6 @@ from pytest_httpserver import HTTPServer from apify_client._literals import ActorJobStatus - from apify_client._models import Run from apify_client.http_clients import HttpClient, HttpClientAsync pytestmark = pytest.mark.usefixtures('http_client_classes') @@ -563,6 +564,144 @@ def test_task_call_redirect_logs_to_custom_logger_sync( ) +@pytest.mark.usefixtures('mock_api', 'propagate_stream_logs', 'reduce_final_timeout_for_status_message_redirector') +async def test_task_call_redirect_logs_to_default_logger_async( + caplog: LogCaptureFixture, + httpserver: HTTPServer, +) -> None: + """Task call logs go to the default redirect logger, named after the Actor of the task run.""" + api_url = httpserver.url_for('/').removesuffix('/') + + logger_name = f'apify.{_MOCKED_ACTOR_NAME} runId:{_MOCKED_RUN_ID}' + logger = logging.getLogger(logger_name) + task_client = ApifyClientAsync(token='mocked_token', api_url=api_url).task(task_id=_MOCKED_TASK_ID) + + with caplog.at_level(logging.DEBUG, logger=logger_name): + await task_client.call() + + assert isinstance(logger.handlers[0].formatter, RedirectLogFormatter) + assert isinstance(logger.handlers[0], logging.StreamHandler) + assert {(record.message, record.levelno) for record in caplog.records} == set( + _EXPECTED_MESSAGES_AND_LEVELS_WITH_STATUS_MESSAGES + ) + + +@pytest.mark.usefixtures('mock_api', 'propagate_stream_logs', 'reduce_final_timeout_for_status_message_redirector') +def test_task_call_redirect_logs_to_default_logger_sync( + caplog: LogCaptureFixture, + httpserver: HTTPServer, +) -> None: + """Task call logs go to the default redirect logger, named after the Actor of the task run.""" + api_url = httpserver.url_for('/').removesuffix('/') + + logger_name = f'apify.{_MOCKED_ACTOR_NAME} runId:{_MOCKED_RUN_ID}' + logger = logging.getLogger(logger_name) + task_client = ApifyClient(token='mocked_token', api_url=api_url).task(task_id=_MOCKED_TASK_ID) + + with caplog.at_level(logging.DEBUG, logger=logger_name): + task_client.call() + + assert isinstance(logger.handlers[0].formatter, RedirectLogFormatter) + assert isinstance(logger.handlers[0], logging.StreamHandler) + assert {(record.message, record.levelno) for record in caplog.records} == set( + _EXPECTED_MESSAGES_AND_LEVELS_WITH_STATUS_MESSAGES + ) + + +@pytest.mark.usefixtures('mock_api', 'propagate_stream_logs') +async def test_task_call_no_redirect_logs_async( + caplog: LogCaptureFixture, + httpserver: HTTPServer, +) -> None: + """Task call with `logger=None` redirects nothing.""" + api_url = httpserver.url_for('/').removesuffix('/') + + logger_name = f'apify.{_MOCKED_ACTOR_NAME} runId:{_MOCKED_RUN_ID}' + task_client = ApifyClientAsync(token='mocked_token', api_url=api_url).task(task_id=_MOCKED_TASK_ID) + + with caplog.at_level(logging.DEBUG, logger=logger_name): + await task_client.call(logger=None) + + assert len(caplog.records) == 0 + + +@pytest.mark.usefixtures('mock_api', 'propagate_stream_logs') +def test_task_call_no_redirect_logs_sync( + caplog: LogCaptureFixture, + httpserver: HTTPServer, +) -> None: + """Task call with `logger=None` redirects nothing.""" + api_url = httpserver.url_for('/').removesuffix('/') + + logger_name = f'apify.{_MOCKED_ACTOR_NAME} runId:{_MOCKED_RUN_ID}' + task_client = ApifyClient(token='mocked_token', api_url=api_url).task(task_id=_MOCKED_TASK_ID) + + with caplog.at_level(logging.DEBUG, logger=logger_name): + task_client.call(logger=None) + + assert len(caplog.records) == 0 + + +@pytest.mark.parametrize( + 'failing_helper', + [ + pytest.param('get_status_message_watcher', id='status-message-watcher'), + pytest.param('get_streamed_log', id='streamed-log'), + ], +) +@pytest.mark.usefixtures('mock_api') +async def test_task_call_returns_run_when_log_redirection_setup_fails_async( + *, + caplog: LogCaptureFixture, + httpserver: HTTPServer, + monkeypatch: pytest.MonkeyPatch, + failing_helper: str, +) -> None: + """A failure to set up log redirection is logged as a warning, and the call still waits for and returns the run.""" + monkeypatch.setattr(RunClientAsync, failing_helper, AsyncMock(side_effect=RuntimeError('Simulated setup failure'))) + api_url = httpserver.url_for('/').removesuffix('/') + task_client = ApifyClientAsync(token='mocked_token', api_url=api_url).task(task_id=_MOCKED_TASK_ID) + + with caplog.at_level(logging.WARNING, logger='apify_client'): + run = await task_client.call() + + assert isinstance(run, Run) + assert run.id == _MOCKED_RUN_ID + assert any( + record.levelno == logging.WARNING and 'without log redirection' in record.message for record in caplog.records + ) + + +@pytest.mark.parametrize( + 'failing_helper', + [ + pytest.param('get_status_message_watcher', id='status-message-watcher'), + pytest.param('get_streamed_log', id='streamed-log'), + ], +) +@pytest.mark.usefixtures('mock_api') +def test_task_call_returns_run_when_log_redirection_setup_fails_sync( + *, + caplog: LogCaptureFixture, + httpserver: HTTPServer, + monkeypatch: pytest.MonkeyPatch, + failing_helper: str, +) -> None: + """A failure to set up log redirection is logged as a warning, and the call still waits for and returns the run.""" + monkeypatch.setattr(RunClient, failing_helper, Mock(side_effect=RuntimeError('Simulated setup failure'))) + api_url = httpserver.url_for('/').removesuffix('/') + task_client = ApifyClient(token='mocked_token', api_url=api_url).task(task_id=_MOCKED_TASK_ID) + + with caplog.at_level(logging.WARNING, logger='apify_client'): + run = task_client.call() + + assert isinstance(run, Run) + assert run.id == _MOCKED_RUN_ID + assert any( + record.levelno == logging.WARNING and 'without log redirection' in record.message for record in caplog.records + ) + + @pytest.mark.usefixtures('mock_api', 'propagate_stream_logs', 'reduce_final_timeout_for_status_message_redirector') async def test_redirect_status_message_async( *,