> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# サンドボックスのログ

> stream_logs() を使用して、サンドボックスのメインプロセスからコンテナーログ (stdout と stderr) をストリーミングします。

以下の例では、`CWSANDBOX_API_KEY` に設定した CoreWeave API アクセストークンを使用します。Forge APIキーによる認証については、[はじめに](/ja/products/sandboxes/get-started) を参照してください。CKS の要件については、[配置モード](/ja/products/sandboxes/placement) を参照してください。

このガイドでは、サンドボックスからコンテナーログを取得する方法を説明します。コンテナーログを使用すると、メインプロセスの動作を監視したり、障害をデバッグしたり、サンドボックスの停止後に出力を確認したりできます。

コンテナーログとは、サンドボックスの**メインプロセス**の stdout と stderr です。`stream_logs()` を使用してストリーミングできます。この関数は、`Sandbox.run()` に渡したコマンドの出力を取得します。`exec()` コマンドの出力は含まれないため、その出力には `Process.stdout` または `Process.stderr` を使用してください。

`stream_logs()` は、ログ行を順に返す `StreamReader` を返します。同期と非同期のどちらでも反復処理できます。

<Note>
  コマンドを指定せずに `Sandbox.run()` を呼び出した場合、サンドボックスのデフォルトコマンドは stdout にも stderr にも書き込まないため、`stream_logs()` は何も出力しません。stdout または stderr に書き込むコマンドを渡してください。
</Note>

<h2 id="retrieve-recent-logs">
  最近のログを取得する
</h2>

`tail_lines` を使用して、履歴全体をストリーミングせずに最新のログ行を取得します。これは実行中のサンドボックスを素早く確認するのに役立ちます。

```python theme={"system"}
for line in sandbox.stream_logs(tail_lines=100):
    print(line, end="")
```

<h2 id="follow-mode">
  フォローモード
</h2>

ログを継続的にストリーミングします。`tail -f` のように動作します。新しいデータが到着するまでイテレーターはブロックします。

```python theme={"system"}
for line in sandbox.stream_logs(follow=True):
    print(line, end="")
```

フォローモードで反復処理を行う際は `Ctrl+C` を押して停止してください。

<h2 id="filter-by-time">
  時間でフィルター
</h2>

`since_time` を渡すと、特定のタイムスタンプ以降のログのみを取得できます。これにより、出力を関心のあるウィンドウに絞り込めます。たとえば、デプロイメントやインシデント以降のログなどです。

```python theme={"system"}
from datetime import datetime, timezone

since = datetime(2026, 2, 20, 14, 0, 0, tzinfo=timezone.utc)
for line in sandbox.stream_logs(since_time=since):
    print(line, end="")
```

<h2 id="timestamps">
  タイムスタンプ
</h2>

`timestamps=True` を設定すると、各行の先頭にサーバーからの ISO 8601 タイムスタンプが付加されます。サーバー側タイムスタンプは、サンドボックスイベントを他のシステムと関連付けるのに役立ちます。

```python theme={"system"}
for line in sandbox.stream_logs(tail_lines=10, timestamps=True):
    print(line, end="")
# 出力: 2026-02-20T14:30:00Z ログ行の例
```

<h2 id="async-iteration">
  Async 反復処理
</h2>

アプリケーションで `asyncio` を使用している場合は、イベントループをブロックしないように、同じ `StreamReader` を `async for` で反復処理してください。

```python theme={"system"}
async for line in sandbox.stream_logs(follow=True):
    print(line, end="")
```

<h2 id="retrieve-logs-from-stopped-sandboxes">
  停止したサンドボックスからログを取得する
</h2>

ログはサンドボックスが停止した後も利用可能なままなので、失敗を調査したり、完了した作業の出力を確認したりできます。完了、失敗、または終了したサンドボックスから過去のログを取得します：

```python theme={"system"}
sb = Sandbox.from_id("sbx-abc123").result()
for line in sb.stream_logs(tail_lines=50):
    print(line, end="")
```

停止したサンドボックスでは、`follow=False` (デフォルト) のみがサポートされます。

<h2 id="see-also">
  関連項目
</h2>

* [コマンドの実行](/ja/products/sandboxes/client/guides/execution): `exec()` を使用したコマンドの実行と出力のストリーミング
* [同期と非同期](/ja/products/sandboxes/client/guides/sync-vs-async): 反復処理のパターン
