# AWS Lambda and CloudWatch Logs

This recipe posts to the [log ingest API](https://developer.watchtower15.com/ingest/logs/), which holds the request contract: the source’s token, the body forms, the answers and the limits.

No dependencies — Node.js 20+ has `fetch` built in.

```js
// Set WT15_INGEST_URL and WT15_INGEST_TOKEN as environment variables. Keep the
// token in Secrets Manager or an encrypted env var, never in source control.
const ENDPOINT = process.env.WT15_INGEST_URL;
const TOKEN = process.env.WT15_INGEST_TOKEN;

export const handler = async (event) => {
    const lines = (event.Records ?? [event]).map((record) => ({
        logged_at: new Date().toISOString(),
        log_level: 'info',
        stream_name: 'orders-lambda',
        message: typeof record === 'string' ? record : JSON.stringify(record)
    }));

    const response = await fetch(ENDPOINT, {
        method: 'POST',
        headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
        body: JSON.stringify({ lines })
    });

    if (!response.ok) {
        // 403 → the token was rotated or revoked. 429 → back off and retry (a 429 after 403s: check the token).
        throw new Error(`WatchTower15 ingest failed: ${response.status} ${await response.text()}`);
    }

    return { ingested: lines.length };
};
```

### From CloudWatch Logs

To mirror an existing log group, put a **subscription filter** on it pointing at a Lambda like the one above. The event arrives base64-encoded and gzipped, so decode it first:

```js
import { gunzipSync } from 'node:zlib';

const payload = JSON.parse(gunzipSync(Buffer.from(event.awslogs.data, 'base64')).toString());
const lines = payload.logEvents.map((e) => ({
    logged_at: new Date(e.timestamp).toISOString(),
    stream_name: payload.logGroup.replace(/^\//, '').replace(/\//g, '.'),
    message: e.message
}));
```

Batches over 1,000 lines need splitting across requests.

Source: https://developer.watchtower15.com/sdks/recipes/aws-lambda/
