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

# /v1/apps/{appId}/logs

> This endpoint streams the console of an application in real time, read-only.

> [!WARNING]
>
> At most 5 streams can be open at the same time per account, and at most 20 new connections can be opened per minute. Close the streams you no longer need.

> [!NOTE]
>
> This endpoint is read-only: it only sends the output of the application. There is no way to send input or commands to the application through it.

## How the stream behaves

1. When the stream opens you receive `ready`, then `clear` and the last `tail` lines (100 by default).
2. After that, every new line arrives as a `log` event as soon as the application writes it.
3. When the application stops or starts you receive `status` with `die` or `start`. After a start you receive `clear` and the first lines of the new run.
4. The server closes every stream after 30 minutes with `end` and `reason: "timeout"`, and also when it loses the connection to the server that runs the application (`worker-lost`) or when your client reads too slowly (`slow-client`). Reconnect when that happens; the permissions are checked again on every connection.

> [!TIP]
>
> Always handle `clear` by discarding what you have shown. That is how you avoid showing the same lines twice after a reconnection.

## Examples

```bash curl theme={null}
curl -N "https://api.camposcloud.com/v1/apps/<appId>/logs?tail=50" \
  -H "Authorization: Bearer <token>"
```

```javascript Node.js 18+ theme={null}
const response = await fetch("https://api.camposcloud.com/v1/apps/<appId>/logs?tail=50", {
  headers: { Authorization: "Bearer <token>", Accept: "text/event-stream" },
});
if (!response.ok) throw new Error((await response.json()).error);

const decoder = new TextDecoder();
let buffer = "";
for await (const chunk of response.body) {
  buffer += decoder.decode(chunk, { stream: true });
  let end;
  while ((end = buffer.indexOf("\n\n")) >= 0) {
    const block = buffer.slice(0, end);
    buffer = buffer.slice(end + 2);
    let event = "message";
    const data = [];
    for (const line of block.split("\n")) {
      if (line.startsWith("event:")) event = line.slice(6).trim();
      else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
    }
    if (data.length === 0) continue; // comments such as ": ping"
    if (event === "clear") console.clear();
    else if (event === "log") console.log(data.join("\n"));
    else if (event === "end") console.log("stream ended:", JSON.parse(data.join("\n")).reason);
  }
}
```

```python Python (requests) theme={null}
import json
import requests

url = "https://api.camposcloud.com/v1/apps/<appId>/logs"
headers = {"Authorization": "Bearer <token>", "Accept": "text/event-stream"}

with requests.get(url, headers=headers, params={"tail": 50}, stream=True, timeout=(10, 70)) as response:
    response.raise_for_status()
    event, data = "message", []
    for line in response.iter_lines(decode_unicode=True):
        if line == "":
            if data:
                text = "\n".join(data)
                if event == "log":
                    print(text)
                elif event == "end":
                    print("stream ended:", json.loads(text)["reason"])
            event, data = "message", []
        elif line.startswith("event:"):
            event = line[6:].strip()
        elif line.startswith("data:"):
            data.append(line[5:].removeprefix(" "))
```

> [!NOTE]
>
> The browser `EventSource` API cannot send the `Authorization` header, so call this endpoint from your server or with `fetch`, never from a public web page: that would expose your API token.


## OpenAPI

````yaml GET /v1/apps/{appId}/logs
openapi: 3.1.0
info:
  title: CamposCloud API Documentation
  description: >-
    This documentation provides an overview of the CamposCloud API, including
    authentication, endpoints, and data structures. It is designed to help
    developers integrate with the CamposCloud platform effectively.
  version: 1.0.0
servers:
  - url: https://api.camposcloud.com
security:
  - bearerAuth: []
paths:
  /v1/apps/{appId}/logs:
    get:
      tags:
        - Applications
      description: >-
        Streams the console of an application in real time, **read-only**. The
        response is a [Server-Sent
        Events](https://html.spec.whatwg.org/multipage/server-sent-events.html)
        stream (`text/event-stream`) that stays open: first the most recent
        lines, then every new line as the application writes it. Nothing can be
        sent to the application through this endpoint.


        The owner of the application, the owner of its team and the members of
        its team can open the stream (the same people who see the console in the
        dashboard).


        Events:


        | Event | Data | Meaning |

        | --- | --- | --- |

        | `ready` | JSON `{ applicationId, name, online, tail }` | Sent once,
        when the stream opens. |

        | `clear` | empty | Discard what you have shown: the most recent lines
        are sent next. Sent after `ready` and again whenever the log is sent
        again (for example after the application restarts). |

        | `log` | text | Output of the application. A block with line breaks is
        sent as several `data:` lines, which SSE clients join with `\n`. |

        | `status` | JSON `{ action }` | Container event, such as `start`,
        `die`, `restart` or `oom`. |

        | `end` | JSON `{ reason, message }` | The server closed the stream.
        `reason` is `timeout`, `error`, `worker-lost` or `slow-client`. |


        A comment line (`: ping`) is sent every 25 seconds to keep the
        connection open.
      parameters:
        - name: appId
          in: path
          required: true
          description: ID of the application.
          schema:
            type: string
            pattern: ^[a-f0-9]{24}$
        - name: tail
          in: query
          required: false
          description: >-
            How many recent lines to send before the live lines. Other query
            parameters are refused.
          schema:
            type: integer
            minimum: 0
            maximum: 500
            default: 100
      responses:
        '200':
          description: >-
            The stream. It stays open until the client disconnects or the server
            sends `end`.
          content:
            text/event-stream:
              schema:
                type: string
              example: >+
                retry: 5000


                event: ready

                data:
                {"applicationId":"64b7f0c2a1b2c3d4e5f60718","name":"my-bot","online":true,"tail":100}


                event: clear

                data: 


                event: log

                data: Bot connected as my-bot#1234


                event: log

                data: Error: something failed

                data:     at main (index.js:10:5)


                : ping


                event: status

                data: {"action":"die"}


                event: end

                data: {"reason":"timeout","message":"The stream reached its
                maximum duration. Reconnect to continue."}

        '400':
          description: >-
            `appId` is not a valid ID, `tail` is not an integer between 0 and
            500, or an unknown query parameter was sent.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error: '''tail'' must be an integer between 0 and 500.'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: You are not the owner of the application nor a member of its team.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error: >-
                  You do not have permission to perform this action on this
                  application.
        '404':
          description: Application not found.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error: >-
                  Application not found or you do not have permission to access
                  it.
        '429':
          description: >-
            Too many streams: at most 5 open at the same time per account, and
            at most 20 new connections per minute.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error: At most 5 log streams can be open at the same time.
        '500':
          $ref: '#/components/responses/InternalError'
components:
  schemas:
    Error:
      type: object
      description: >-
        Every error returned by the API has this shape. The message can be in
        English or in Portuguese depending on the endpoint.
      required:
        - error
      properties:
        error:
          type: string
          description: Human readable description of the error.
          example: Application not found.
  responses:
    Unauthorized:
      description: >-
        The `Authorization` header is missing or malformed, or the API token is
        invalid.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error: Invalid developer token
    InternalError:
      description: >-
        Unexpected error. On endpoints that do not document a `400` for it, this
        is also returned when an ID in the URL is not a valid identifier.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error: Internal server error. Please try again later.
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: 'Your CamposCloud API token, sent as `Authorization: Bearer <token>`.'

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.