Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
9a702a2
feat: redirect run logs from a given time and resume after the platfo…
claude Nov 24, 2026
80e1492
refactor: drop stacklevel handling from the `from_start` deprecation …
claude Nov 25, 2026
bdfe0e8
feat: expose `StreamedLog.last_redirected_at` and resume reopened str…
claude Nov 25, 2026
ef37604
test: e2e test of resuming log redirection after the redirecting Acto…
claude Nov 25, 2026
acb39aa
test: remove the one-off reboot e2e test of log redirection
claude Nov 25, 2026
79aaea6
test: e2e test of log redirection from a run that stays silent for si…
claude Nov 25, 2026
d49cecf
test: run the silent-run log redirection e2e test in a redirecting Actor
claude Nov 25, 2026
5040025
test: give both Actor runs of the silent-run e2e test enough time
claude Nov 25, 2026
95e0fe7
test: remove the one-off silent-run e2e test of log redirection
claude Nov 25, 2026
7cbea01
refactor: reopen a closed log stream after a fixed pause instead of a…
claude Nov 25, 2026
86429bf
refactor: stop log redirection once the run has finished, without a c…
claude Nov 25, 2026
3133679
Format
Pijukatel Nov 25, 2026
c632146
refactor: reopen a log stream only when it broke off
claude Nov 25, 2026
3d4b57f
fix: do not reopen a log stream when processing its data fails
claude Nov 25, 2026
8a0aedb
refactor: reopen a log stream only after a transient transport error
claude Nov 25, 2026
f0517a9
fix: keep lines sharing the last timestamp on reopen, and stop reopen…
claude Nov 27, 2026
2729297
docs: drop the v4 upgrading guide until v4 is planned
claude Nov 27, 2026
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
21 changes: 21 additions & 0 deletions docs/02_concepts/06_logging.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import RedirectCallAsyncExample from '!!raw-loader!./code/06_redirect_call_async
import RedirectCallSyncExample from '!!raw-loader!./code/06_redirect_call_sync.py';
import RedirectRunAsyncExample from '!!raw-loader!./code/06_redirect_run_async.py';
import RedirectRunSyncExample from '!!raw-loader!./code/06_redirect_run_sync.py';
import RedirectResumeAsyncExample from '!!raw-loader!./code/06_redirect_resume_async.py';
import RedirectResumeSyncExample from '!!raw-loader!./code/06_redirect_resume_sync.py';

import ApiLink from '@theme/ApiLink';

Expand Down Expand Up @@ -74,3 +76,22 @@ For a run started with <ApiLink to="class/ActorClient#start">`ActorClient.start`
</CodeBlock>
</TabItem>
</Tabs>

By default, the whole log of the run is redirected. To redirect only part of it, pass a `datetime` as `since`, and only the lines logged at that time or later are redirected. A naive `datetime` is treated as UTC. The deprecated `from_start` argument still works: `from_start=False` is the same as `since=datetime.now(tz=UTC)`.

The platform cuts off a log stream that has carried no data for several minutes, even when the run is still going. When that happens, the client reopens the stream. The API can't continue a stream from a given point, so the reopened stream delivers the log from its start, and the client skips everything up to <ApiLink to="class/StreamedLog#last_redirected_at">`StreamedLog.last_redirected_at`</ApiLink>, the timestamp of the last redirected line. A stream that ends on its own has delivered the whole log of a finished run, and the client doesn't open it again.

The same property lets you continue the redirection in another process, for example after the Actor that redirects the log reboots. Save `last_redirected_at` before the reboot, and afterwards pass it plus one millisecond as `since`. Log timestamps have millisecond precision, so this skips the last redirected line. It would also skip another line logged in that same millisecond and not yet redirected, which is rare.

<Tabs>
<TabItem value="AsyncExample" label="Async client" default>
<CodeBlock className="language-python">
{RedirectResumeAsyncExample}
</CodeBlock>
</TabItem>
<TabItem value="SyncExample" label="Sync client">
<CodeBlock className="language-python">
{RedirectResumeSyncExample}
</CodeBlock>
</TabItem>
</Tabs>
28 changes: 28 additions & 0 deletions docs/02_concepts/code/06_redirect_resume_async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from datetime import datetime, timedelta

from apify_client import ApifyClientAsync

TOKEN = 'MY-APIFY-TOKEN'
RECORD_KEY = 'LOG_REDIRECTED_UNTIL'


async def main() -> None:
apify_client = ApifyClientAsync(TOKEN)
run_client = apify_client.run('MY-RUN-ID')
store_client = apify_client.key_value_store('MY-STORE-ID')

# After a reboot, continue after the last line redirected before it.
record = await store_client.get_record(RECORD_KEY)
since = None
if record:
since = datetime.fromisoformat(record['value']) + timedelta(milliseconds=1)

streamed_log = await run_client.get_streamed_log(since=since)
async with streamed_log:
await run_client.wait_for_finish()

# Before a reboot, save how far the redirection got. Here it is saved once the
# run finishes; save it on your own reboot or migration signal instead.
if streamed_log.last_redirected_at:
redirected_until = streamed_log.last_redirected_at.isoformat()
await store_client.set_record(RECORD_KEY, redirected_until)
28 changes: 28 additions & 0 deletions docs/02_concepts/code/06_redirect_resume_sync.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from datetime import datetime, timedelta

from apify_client import ApifyClient

TOKEN = 'MY-APIFY-TOKEN'
RECORD_KEY = 'LOG_REDIRECTED_UNTIL'


def main() -> None:
apify_client = ApifyClient(TOKEN)
run_client = apify_client.run('MY-RUN-ID')
store_client = apify_client.key_value_store('MY-STORE-ID')

# After a reboot, continue after the last line redirected before it.
record = store_client.get_record(RECORD_KEY)
since = None
if record:
since = datetime.fromisoformat(record['value']) + timedelta(milliseconds=1)

streamed_log = run_client.get_streamed_log(since=since)
with streamed_log:
run_client.wait_for_finish()

# Before a reboot, save how far the redirection got. Here it is saved once the
# run finishes; save it on your own reboot or migration signal instead.
if streamed_log.last_redirected_at:
redirected_until = streamed_log.last_redirected_at.isoformat()
store_client.set_record(RECORD_KEY, redirected_until)
6 changes: 4 additions & 2 deletions docs/02_concepts/code/06_redirect_run_async.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from datetime import UTC, datetime

from apify_client import ApifyClientAsync

TOKEN = 'MY-APIFY-TOKEN'
Expand All @@ -20,8 +22,8 @@ async def main() -> None:
actor_run = await actor_client.start()
run_client = apify_client.run(actor_run.id)

# With `from_start=False`, only log lines written from now on are redirected.
streamed_log = await run_client.get_streamed_log(from_start=False)
# With `since`, only log lines written at that time or later are redirected.
streamed_log = await run_client.get_streamed_log(since=datetime.now(tz=UTC))
streamed_log.start()
# Do other work while the run's log is redirected.
await streamed_log.stop()
6 changes: 4 additions & 2 deletions docs/02_concepts/code/06_redirect_run_sync.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from datetime import UTC, datetime

from apify_client import ApifyClient

TOKEN = 'MY-APIFY-TOKEN'
Expand All @@ -20,8 +22,8 @@ def main() -> None:
actor_run = actor_client.start()
run_client = apify_client.run(actor_run.id)

# With `from_start=False`, only log lines written from now on are redirected.
streamed_log = run_client.get_streamed_log(from_start=False)
# With `since`, only log lines written at that time or later are redirected.
streamed_log = run_client.get_streamed_log(since=datetime.now(tz=UTC))
streamed_log.start()
# Do other work while the run's log is redirected.
streamed_log.stop()
40 changes: 26 additions & 14 deletions src/apify_client/_resource_clients/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import random
import string
import time
from datetime import timedelta
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, Literal

from apify_client._docs import docs_group
Expand All @@ -14,7 +14,7 @@
from apify_client._pagination import DEFAULT_CHUNK_SIZE
from apify_client._resource_clients._resource_client import _TERMINAL_STATUSES, ResourceClient, ResourceClientAsync
from apify_client._status_message_watcher import StatusMessageWatcher, StatusMessageWatcherAsync
from apify_client._streamed_log import StreamedLog, StreamedLogAsync
from apify_client._streamed_log import StreamedLog, StreamedLogAsync, resolve_since
from apify_client._utils.encoding import encode_key_value_store_record_value
from apify_client._utils.http import response_to_dict, to_safe_id
from apify_client._utils.time import to_seconds
Expand Down Expand Up @@ -350,23 +350,29 @@ def get_streamed_log(
self,
to_logger: logging.Logger | None = None,
*,
from_start: bool = True,
since: datetime | None = None,
from_start: bool | None = None,
timeout: Timeout = 'long',
) -> StreamedLog:
"""Get `StreamedLog` instance that can be used to redirect logs.

`StreamedLog` can be explicitly started and stopped or used as a context manager.
`StreamedLog` can be explicitly started and stopped or used as a context manager. When the platform closes
the log stream while the run is still going, for example after the run has logged nothing for several
minutes, the stream is reopened and the redirection resumes after the last redirected message.

Args:
to_logger: `Logger` used for logging the redirected messages. If not provided, a new logger is created
from_start: If `True`, all logs from the start of the Actor run will be redirected. If `False`, only newly
arrived logs will be redirected. This can be useful for redirecting only a small portion of relevant
logs for long-running Actors in stand-by.
since: Redirect only the log messages logged at this time or later. A naive datetime is treated as UTC.
If `None`, the whole log is redirected. Redirecting only the recent messages can be useful for
long-running Actors, such as Server Actors.
from_start: Deprecated, use `since` instead. `True` is the same as `since=None`, and `False` the same as
`since=datetime.now(tz=UTC)`. Will be removed in v4.
timeout: Timeout for the API HTTP request.

Returns:
`StreamedLog` instance for redirected logs.
"""
since = resolve_since(since=since, from_start=from_start)
Comment thread
vdusek marked this conversation as resolved.
Resolved
run_data = self.get(timeout=timeout)
run_id = f'runId:{run_data.id}' if run_data and run_data.id else ''

Expand All @@ -387,7 +393,7 @@ def get_streamed_log(
name = ' '.join(part for part in (actor_name, run_id) if part)
to_logger = create_redirect_logger(f'apify.{name}')

return StreamedLog(log_client=self.log(), to_logger=to_logger, from_start=from_start)
return StreamedLog(log_client=self.log(), to_logger=to_logger, since=since)

def charge(
self,
Expand Down Expand Up @@ -943,23 +949,29 @@ async def get_streamed_log(
self,
to_logger: logging.Logger | None = None,
*,
from_start: bool = True,
since: datetime | None = None,
from_start: bool | None = None,
timeout: Timeout = 'long',
) -> StreamedLogAsync:
"""Get `StreamedLog` instance that can be used to redirect logs.

`StreamedLog` can be explicitly started and stopped or used as a context manager.
`StreamedLog` can be explicitly started and stopped or used as a context manager. When the platform closes
the log stream while the run is still going, for example after the run has logged nothing for several
minutes, the stream is reopened and the redirection resumes after the last redirected message.

Args:
to_logger: `Logger` used for logging the redirected messages. If not provided, a new logger is created
from_start: If `True`, all logs from the start of the Actor run will be redirected. If `False`, only newly
arrived logs will be redirected. This can be useful for redirecting only a small portion of relevant
logs for long-running Actors in stand-by.
since: Redirect only the log messages logged at this time or later. A naive datetime is treated as UTC.
If `None`, the whole log is redirected. Redirecting only the recent messages can be useful for
long-running Actors, such as Server Actors.
from_start: Deprecated, use `since` instead. `True` is the same as `since=None`, and `False` the same as
`since=datetime.now(tz=UTC)`. Will be removed in v4.
timeout: Timeout for the API HTTP request.

Returns:
`StreamedLog` instance for redirected logs.
"""
since = resolve_since(since=since, from_start=from_start)
run_data = await self.get(timeout=timeout)
run_id = f'runId:{run_data.id}' if run_data and run_data.id else ''

Expand All @@ -980,7 +992,7 @@ async def get_streamed_log(
name = ' '.join(part for part in (actor_name, run_id) if part)
to_logger = create_redirect_logger(f'apify.{name}')

return StreamedLogAsync(log_client=self.log(), to_logger=to_logger, from_start=from_start)
return StreamedLogAsync(log_client=self.log(), to_logger=to_logger, since=since)

async def charge(
self,
Expand Down
Loading
Loading