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

# WebSocket Connection

> Real-time log streaming via WebSocket

After starting a streaming session, connect to the WebSocket endpoint to receive real-time logs.

## Connection

```
wss://api.logfleet.io/api/v1/stream/ws/{sessionId}
```

### Authentication

Include your JWT token as a query parameter:

```
wss://api.logfleet.io/api/v1/stream/ws/{sessionId}?token={jwt_token}
```

## Message Format

### Log Messages

```json theme={null}
{
  "type": "log",
  "timestamp": "2024-01-15T10:30:00.123Z",
  "level": "info",
  "message": "Request processed successfully",
  "source": "nginx",
  "metadata": {
    "request_id": "abc123",
    "status_code": 200
  }
}
```

### Control Messages

```json theme={null}
{
  "type": "control",
  "event": "session_ending",
  "reason": "timeout",
  "seconds_remaining": 30
}
```

## Example

<CodeGroup>
  ```javascript JavaScript theme={null}
  const token = "your-jwt-token";
  const sessionId = "session-uuid";

  const ws = new WebSocket(
    `wss://api.logfleet.io/api/v1/stream/ws/${sessionId}?token=${token}`
  );

  ws.onopen = () => {
    console.log("Connected to log stream");
  };

  ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    if (data.type === "log") {
      console.log(`[${data.level}] ${data.message}`);
    } else if (data.type === "control") {
      console.log(`Control: ${data.event}`);
    }
  };

  ws.onclose = () => {
    console.log("Stream ended");
  };
  ```

  ```python Python theme={null}
  import websockets
  import asyncio
  import json

  async def stream_logs(session_id, token):
      uri = f"wss://api.logfleet.io/api/v1/stream/ws/{session_id}?token={token}"

      async with websockets.connect(uri) as ws:
          async for message in ws:
              data = json.loads(message)
              if data["type"] == "log":
                  print(f"[{data['level']}] {data['message']}")
              elif data["type"] == "control":
                  print(f"Control: {data['event']}")

  asyncio.run(stream_logs("session-uuid", "your-jwt-token"))
  ```
</CodeGroup>

## Session Lifecycle

1. **Start**: Call `POST /api/v1/stream/start` to create a session
2. **Connect**: Open WebSocket connection with session ID
3. **Stream**: Receive log messages in real-time
4. **Warning**: Receive `session_ending` control message 30 seconds before timeout
5. **End**: Connection closes when session times out or is stopped

<Warning>
  Sessions automatically terminate after the specified timeout (default: 5 minutes, max: 1 hour).
  This prevents forgotten streams from running indefinitely.
</Warning>
