Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/02_concepts/06_logging.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <ApiLink to="class/ActorClient#call">`ActorClient.call`</ApiLink>, 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 <ApiLink to="class/ActorClient#call">`ActorClient.call`</ApiLink> or a task with <ApiLink to="class/TaskClient#call">`TaskClient.call`</ApiLink>, 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.
Expand Down
30 changes: 2 additions & 28 deletions src/apify_client/_resource_clients/actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
69 changes: 68 additions & 1 deletion src/apify_client/_resource_clients/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
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
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
Expand Down Expand Up @@ -598,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):
Expand Down Expand Up @@ -1160,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)
19 changes: 16 additions & 3 deletions src/apify_client/_resource_clients/task.py
Original file line number Diff line number Diff line change
@@ -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 (
Expand All @@ -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 (
Expand Down Expand Up @@ -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',
Comment thread
Pijukatel marked this conversation as resolved.
Resolved
timeout: Timeout = 'no_timeout',
) -> Run | None:
"""Start a task and wait for it to finish before returning the Run object.
Expand Down Expand Up @@ -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 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.
Expand Down Expand Up @@ -397,7 +403,8 @@ def call(
http_client=self._http_client,
client_registry=self._client_registry,
)
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.
Expand Down Expand Up @@ -775,6 +782,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.
Expand Down Expand Up @@ -809,6 +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 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.
Expand All @@ -835,7 +847,8 @@ 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)

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.
Expand Down
25 changes: 11 additions & 14 deletions tests/unit/test_call_poll_timeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')])
Expand All @@ -16,11 +17,10 @@ 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)
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)
Expand All @@ -34,11 +34,10 @@ 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)
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)
Expand All @@ -49,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)
Expand All @@ -65,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)
Expand Down
Loading
Loading