# Logs

> Send structured logs from your services with an SDK logger, OpenTelemetry or JSON lines, then search them, tail them live, link them to traces and people, and alert on them.

Source: https://apphelm.dev/docs/logs

AppHelm stores your services' logs next to their errors, traces and replays. Each line has a level, a message, a service and attributes. A line that carries a trace id links to its trace and to issues in that trace; a line that carries a person's id links to that person. You can search lines, chart them by level, tail them live, save searches and alert when a search matches too many lines.

Logs are metered in bytes, separately from your event allowance (see [Plans and retention](#plans-and-retention)).

## Send logs

There are three ways in. Use whichever fits; they all land in the same place.

| Way | Best for |
| --- | --- |
| The SDK's `logger` | Apps already using an AppHelm SDK. Lines are batched, scrubbed and linked to the active trace for you. |
| OpenTelemetry (OTLP/HTTP) | Services that already export with OpenTelemetry, a Collector, Vector or Fluent Bit |
| JSON lines | Anything that writes JSON logs: pino, structlog, a log shipper, a script |

Every route takes a server key (`ahl_live_…`) with `logs:write` or `events:write`, so existing server and mobile keys can send logs without changes. The browser SDK sends with its public project key. Keys can't read logs unless they also hold `logs:read`.

### The SDK logger

Logging is on as soon as the client exists; there is no switch to turn on. The default minimum level is `info`.

Node.js:
```ts
import { Apphelm } from "@sansavision/apphelm";

const apphelm = new Apphelm({ apiKey: process.env.APPHELM_API_KEY!, productId: "prd_…", service: "api", environment: "production" });
apphelm.logger.info("Order paid", { order_id: 42, amount: 9.5 });
apphelm.logger.error("Payment failed", { orderId, distinct_id: user.id });
const requestLog = apphelm.logger.child({ request_id }); // attributes on every line
```

JavaScript (browser):
```js
const apphelm = createBrowserSdk({ key: "ahl_pub_…", workspaceId: "org_…", productId: "prd_…", logsService: "shop-web" });
apphelm.logger.info("Checkout opened", { plan: "pro" });
apphelm.logger.warn(apphelm.logger.fmt`Payment ${paymentId} retried ${count} times`);
```

React:
```tsx
const apphelm = useApphelm();
apphelm?.logger.info("Checkout opened", { plan: "pro" });
// Set logsService, logsMinLevel and beforeSendLog in ApphelmProvider's options.
```

Next.js:
```tsx
"use client";
import { useApphelm } from "@sansavision/apphelm/react";

const apphelm = useApphelm();
apphelm?.logger.info("Checkout opened", { plan: "pro" });
// On the server, use the Node client from lib/apphelm.ts: apphelm.logger.error(…)
```

Vue / Nuxt:
```ts
apphelm.logger.info("Checkout opened", { plan: "pro" }); // the client from createBrowserSdk
```

Svelte / SvelteKit:
```ts
apphelm.logger.info("Checkout opened", { plan: "pro" }); // the client from createBrowserSdk
```

Python:
```python
import apphelm

apphelm.init(api_key="ahl_live_…", workspace_id="org_…", product_id="prd_…", logs_service="api")
apphelm.logger.info("Order paid", {"order_id": 42})
```

iOS (Swift):
```swift
var options = ApphelmOptions(apiKey: "ahl_live_…", workspaceId: "org_…", productId: "prd_…")
options.logsService = "shop-ios"
let apphelm = ApphelmClient(options: options)
apphelm.logger.info("Signed in", attributes: ["method": "passkey"])
```

Android (Kotlin):
```kotlin
Apphelm.logger.info("Checkout opened", mapOf("items" to 3, "coupon" to true))
val cart = Apphelm.logger.child(mapOf("component" to "cart"))
```

Flutter:
```dart
final log = Apphelm.logger; // after Apphelm.setup
log.info('Checkout started', {'order_id': 42, 'total': 19.9});
```

Java / Kotlin (JVM):
```kotlin
apphelm.logger.info("Invoice sent", mapOf("invoice_id" to 42))
```

Go:
```go
logger := client.Logger().With(map[string]any{"component": "billing"})
logger.Info(ctx, "invoice sent", map[string]any{"invoice_id": inv.ID, "amount": 42.5})
```

Ruby:
```ruby
APPHELM.logger.info("Invoice sent", invoice_id: 42, amount: 9.5)
```

PHP:
```php
$log = $apphelm->logger();
$log->info('Order placed', ['order_id' => $order->id, 'total' => 42.5]);
```

.NET (C#):
```csharp
apphelm.Logger.Info("Order paid", new Dictionary<string, object?> { ["order_id"] = 42, ["amount"] = 9.5 });
```

Rust:
```rust
let logger = apphelm.logger();
logger.info("Invoice sent", json!({ "invoice_id": "inv_42", "amount": 1200 }));
```

Elixir:
```elixir
Apphelm.Logger.info("Payment captured", %{order_id: 42, amount: 19.99})
```

HTTP (curl):
```bash
curl -X POST "https://apphelm.dev/api/v1/logs/jsonl?service=worker" \
  -H "Authorization: Bearer $APPHELM_API_KEY" \
  -H "x-apphelm-product: prd_…" \
  --data-binary $'{"level":"error","msg":"Payment failed","order_id":42,"trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"}\n'
# 202 { "accepted": 1, "rejected": 0, "bytes": … }
```

**Only for React Native / Expo:**

**React Native has no logger yet.** Send lines from your backend, or post them to the JSON lines endpoint yourself with a key that has only `events:write`.

Every logger has the six levels `trace`, `debug`, `info`, `warn`, `error` and `fatal`, a `child` that adds attributes to every line, and a `flush`. Lines logged inside an active span or transaction carry its trace and span ids.

### Bridge your existing logger

Keep your logging library; send its output to AppHelm too.

Node.js:
```ts
import pino from "pino";
import Transport from "winston-transport";
import { pinoDestination, winstonTransport, captureConsole } from "@sansavision/apphelm/server";

const log = pino({}, pinoDestination(apphelm.logger));                          // pino
const transport = new (winstonTransport(Transport))({ logger: apphelm.logger }); // winston: pass your winston-transport
const restore = captureConsole(apphelm.logger);                                  // console.log/info/warn/error
```

Python:
```python
import logging
from apphelm_logging import ApphelmLogHandler

logging.getLogger().addHandler(ApphelmLogHandler(api_key="ahl_live_…", product_id="prd_…", service="worker"))
logging.getLogger(__name__).error("Payment failed", extra={"order_id": 42, "distinct_id": user_id})
```

Android (Kotlin):
```kotlin
Timber.plant(ApphelmTimberTree()) // info and above become log lines, with log.tag
```

Flutter:
```dart
Logger.root.onRecord.listen(Apphelm.logger.onLoggingRecord); // package:logging
final stop = Apphelm.logger.captureDebugPrint();              // debugPrint too
```

Go:
```go
slog.SetDefault(slog.New(client.SlogLogHandler(slog.NewJSONHandler(os.Stderr, nil), slog.LevelInfo)))
```

Ruby:
```ruby
Rails.logger.broadcast_to(Apphelm.logs_logger(level: :info))
```

PHP:
```php
$monolog->pushHandler(new \Apphelm\Integration\MonologHandler($apphelm, level: 'info'));
// Laravel, config/logging.php: 'apphelm' => ['driver' => 'custom', 'via' => \Apphelm\Laravel\LogChannel::class],
```

.NET (C#):
```csharp
builder.Logging.AddApphelmLogs(options => { options.MinimumLevel = LogLevel.Information; });
```

Rust:
```rust
tracing_subscriber::registry()
    .with(apphelm::ApphelmTracingLayer::new(&apphelm).logs(LevelFilter::INFO))
    .init(); // feature "tracing"; or ApphelmLogger for the log crate (feature "log")
```

Elixir:
```elixir
:logger.add_handler(:apphelm_logs, Apphelm.LogsHandler, %{level: :info, config: %{name: Apphelm, metadata: [:request_id]}})
```

Some bridges have a twin that records breadcrumbs, not log lines: `builder.Logging.AddApphelm()` in .NET, `Apphelm.instrument_logger!` in Ruby, `Apphelm.LoggerHandler` in Elixir, `BreadcrumbLogger` in PHP. Use the ones above for log lines. The pino, winston, Timber, Monolog and `tracing` libraries are your own dependencies; AppHelm's packages don't install them.

**Only for Node.js:**

**Cloudflare Workers.** A Worker can't run a timer between requests. Create the logger with `createLogger({ apiKey, productId, waitUntil: ctx.waitUntil.bind(ctx) })` from `@sansavision/apphelm/server`, or `await apphelm.logger.flush()` inside `ctx.waitUntil` before you return.

### Logger options

| Option (Node, browser, mobile) | Python, Ruby, Elixir, Rust | Go, .NET | Default | What it does |
| --- | --- | --- | --- | --- |
| `logsMinLevel` | `logs_min_level` | `LogsMinLevel` | `info` | Lines below it are not sent |
| `logsService` (Node: `service`) | `logs_service` | `LogsService` | `unknown_service` (browser: `browser`; Android: the package name) | The `service.name` lines are grouped by |
| `beforeSendLog` | `before_send_log` | `BeforeSendLog` | none | Change a line or drop it (return null). Runs after scrubbing |
| `release`, `environment` | same | same | none | Sent as `service.version` and `deployment.environment` |
| `enabled: false` | `enabled=False` | | on | Sends nothing at all |

`createLogger` on Node (and `ApphelmLogHandler` in Python) take the shorter names `minLevel`, `service` and `beforeSend`. Batching is the same everywhere outside the browser: a batch every 2 seconds or at 500 lines, a queue of 10,000 lines (the oldest is dropped when full), one retry when AppHelm is throttled or unavailable. Refused or dropped lines are counted in `logger.dropped`.

**Only for JavaScript (browser), React, Next.js, Vue / Nuxt, Svelte / SvelteKit:**

**In the browser,** lines need analytics consent: nothing is queued before `setConsent({ analytics: true })`, and withdrawing consent drops queued lines. Batches go every 2 seconds or at 100 lines, at most 60 KB each, and are flushed when the page is hidden. The queue holds 1,000 lines. Messages are cut to 4,000 characters and attribute strings to 1,000. Each line carries `url.path` (without the query).

### OpenTelemetry

`POST https://apphelm.dev/api/v1/logs` is an OTLP/HTTP logs endpoint. It takes an `ExportLogsServiceRequest` as protobuf (`application/x-protobuf`) or JSON (`application/json`), optionally gzipped.

```bash
OTEL_LOGS_EXPORTER=otlp
OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=http/protobuf        # or http/json
OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://apphelm.dev/api/v1/logs
OTEL_EXPORTER_OTLP_LOGS_HEADERS="authorization=Bearer ahl_live_…,x-apphelm-product=prd_…"
OTEL_EXPORTER_OTLP_LOGS_COMPRESSION=gzip
OTEL_SERVICE_NAME=api
OTEL_RESOURCE_ATTRIBUTES=service.version=1.42.0,deployment.environment=production
```

The same settings work in an OpenTelemetry Collector (`otlphttp` exporter with `logs_endpoint` and `headers`) or any OTLP shipper. AppHelm also accepts OTLP traces, at `/api/v1/traces` ([Tracing](https://apphelm.dev/docs/tracing#send-opentelemetry-traces)), so a base endpoint of `https://apphelm.dev/api` works for both. There is no OTLP metrics endpoint: export metrics elsewhere.

The response is OTLP's: empty on success, or `partialSuccess` with `rejectedLogRecords` and an `errorMessage` when some records could not be read.

### JSON lines

`POST https://apphelm.dev/api/v1/logs/jsonl` takes newline-delimited JSON, a JSON array, or `{ "logs": [...] }`. It reads the fields loggers already write:

| Field | Read from |
| --- | --- |
| Time | `timestamp`, `time`, `ts`, `@timestamp`, `datetime`, `date` (ISO text, or epoch seconds, ms, µs or ns) |
| Level | `level`, `severity`, `levelname`, `lvl`, `log.level`, `severity_text` (text, or pino's numbers) |
| Message | `message`, `msg`, `body`, `log`, `text`, structlog's `event` |
| Service | `service`, `service.name`, `service_name`, `serviceName`, or `?service=` on the URL |
| Trace | `trace_id`, `traceId`, `trace.id`, `dd.trace_id`, and the same for span ids |
| Person and session | `distinct_id`, `user.id`, `enduser.id`, `user_id`; `session_id`, `session.id`, `$session_id` |

Everything else becomes attributes. It answers `202 { accepted, rejected, bytes }`.

### Which product

Lines go to the key's only product, or the product named by the `x-apphelm-product` header, `?productId=`, or the `apphelm.product_id` resource attribute. A key that covers several products and names none gets `422 product_required`.

## What happens to a line

1. **Levels are normalised.** OpenTelemetry severity numbers map in blocks of four (1–4 trace, 5–8 debug, 9–12 info, 13–16 warn, 17–20 error, 21–24 fatal). Text levels are understood too: `warning` and `notice` are warn, `critical` and `panic` are fatal, `verbose` is trace. Anything unknown is info.
2. **Attributes are flattened** to dotted keys, three levels deep: at most 64 per line, keys up to 100 characters, values up to 1,000. Deeper values and arrays become JSON text. Messages are cut to 8,000 characters.
3. **Timestamps are checked.** A line more than 7 days old or 10 minutes in the future is stored at its arrival time, with the original kept as `apphelm.original_timestamp`.
4. **Ids are linked.** A trace and span id link the line to its trace. A person id (`distinct_id`, `user.id` and the others above) is hashed and the id itself is not stored. A session id links the line to its replay.
5. **Secrets are removed.** API keys (AppHelm, OpenAI, Anthropic, Stripe, AWS, GitHub, Slack, Google), JWTs, private keys, bearer and basic credentials, `password=` style values, secrets in URLs, emails and long hex tokens are replaced in the message and every string attribute. Attributes named like secrets (`password`, `token`, `authorization`, `cookie`, `api_key`…) become `[redacted]`. Then your product's [scrubbing rules](https://apphelm.dev/docs/privacy#scrubbing-rules-on-the-server) apply.

The SDKs scrub the message and attributes on the device too, before `beforeSendLog` sees them. Trace, span, session and person ids are left alone so they still link.

## Search logs

Open **Logs** in the app (under Reliability). The search box takes words, phrases and filters, all joined with AND:

| Write | Matches |
| --- | --- |
| `timeout` | The whole word, any case, in the message or a short attribute. Dotted and hyphenated words match by part (`example` finds `api.example.com`) |
| `"connection refused"` | The phrase |
| `time*` | A word prefix (at least 2 characters; reads more data) |
| `-healthcheck`, `-"GET /health"` | Leaves those lines out |
| `level:error`, `level:warn,error`, `level>=warn`, `-level:debug` | Levels (`severity:` works too) |
| `service:api`, `service:api,web`, `-service:cron` | Services |
| `key=value`, `key!=value`, `key:value`, `key>10`, `key<=2.5` | Attributes or resource attributes (comparisons are numeric) |
| `key:*`, `-key:*` | Lines with or without that attribute |
| `trace:<32 hex>`, `span:<16 hex>`, `session:<id>` | Linked ids |
| `person:<cus_ id>`, `person:<distinct id>` | One person's lines (a distinct id is hashed before searching) |

A search is at most 1,000 characters and 20 parts. A part AppHelm can't read is reported as `422 invalid_log_query` with that part, never guessed at.

- **Range:** up to 90 days; the default is the last hour.
- **Histogram:** lines per time bucket, by level. When the search is only levels and services it is exact from per-minute counts; otherwise it counts lines in part of the range and says so.
- **Partial results:** a search reads up to 40 stored batches per page. When it stops early it says how far back it searched ("searched back to …") and **Load older** continues.
- **Live tail:** new lines every 2.5 seconds while the tab is visible. When lines arrive faster than it can show, it skips to the newest and says so.
- **Line detail:** every attribute, with links to the trace, the issue, the person and the replay when the line carries their ids.

### Saved searches

Save a search with its time range to share it with everyone who can see the product, up to 50 per product. Members who can triage issues save them; viewers run them.

## Log alerts

A log alert counts the lines matching a search over a window and fires when the count is **above** the threshold. It resolves when the count is no longer above it.

1. Search for the lines you care about (`level:error service:checkout`).
2. Choose **Create alert**, set the threshold (lines) and the window (5 to 1,440 minutes), and pick channels: email, Slack or webhook.

Alerts are checked every five minutes. Searches of only levels and services are counted exactly; searches with words, attributes or ids read the stored lines and allow windows of up to 60 minutes. A count from an incomplete read can fire an alert but never resolve one. Firing and resolving send the `log.alert` and `log.resolved` notifications and signed webhook events, linking to the search. See [Alerts and notifications](https://apphelm.dev/docs/alerts).

Owners and admins create alerts, up to 20 per product. After creation you can change the name, the threshold and whether it is on; to change the search, window or channels, create a new alert.

## Read logs through the API

HTTP (curl):
```bash
# Search
curl "https://apphelm.dev/api/v1/logs?productId=prd_…&q=level:error%20service:api&minutes=60&limit=50" \
  -H "Authorization: Bearer $APPHELM_API_KEY"

# Counts over time
curl "https://apphelm.dev/api/v1/logs/histogram?productId=prd_…&q=level:error&minutes=1440" \
  -H "Authorization: Bearer $APPHELM_API_KEY"
```

| Endpoint | Scope |
| --- | --- |
| `GET /logs`, `/logs/histogram`, `/logs/tail`, `/logs/{id}` | `logs:read` |
| `GET /logs/saved-searches`, `/logs/alerts`, `/logs/alerts/{id}` | `logs:read` |
| `POST`, `PATCH`, `DELETE` saved searches and alerts | `analytics:write` (explicit-only), acting as the key's creator; alerts need an owner or admin; creates need an `Idempotency-Key` |

Search pages hold up to 100 lines (default 50). The [MCP server](https://apphelm.dev/docs/mcp) has `apphelm_search_logs`, `apphelm_get_log_histogram`, `apphelm_get_log` and `apphelm_list_log_alerts`, all under `logs:read`. Full parameters are in the [API reference](https://apphelm.dev/docs/api).

## Sentry SDK logs

Sentry SDKs pointed at an AppHelm DSN can send their logs (`log` envelope items) with a server key: up to 1,000 lines per item. AppHelm drops the user's email, name, username and IP, request headers and URL queries from their attributes. Logs sent with a browser key's DSN are dropped. See [Migrate from Sentry](https://apphelm.dev/docs/migrate-sentry).

## Plans and retention

Logs are metered in bytes as stored (after redaction, before compression), per workspace and calendar month:

| Plan | Logs a month | Kept for |
| --- | ---: | ---: |
| Free | 1 GiB | 7 days |
| Builder | 10 GiB | 14 days |
| Portfolio | 50 GiB | 30 days |
| Scale | 250 GiB | 90 days |

The Logs page shows the month's use and warns at 90%. A request that doesn't fit the allowance is refused whole with `429 log_limit` and `Retry-After: 3600`; the SDKs drop such batches instead of retrying. Lines older than the plan's retention are deleted every few minutes.

A [privacy deletion](https://apphelm.dev/docs/privacy#privacy-requests) removes a person's log lines too, and a profile export includes up to 1,000 of them.

## Limits

| Limit | Value |
| --- | --- |
| Request body | 5 MB (20 MB unzipped with `Content-Encoding: gzip`); the browser 256 KB |
| Lines per request | 10,000 (more are counted as rejected) |
| One request's time spread | Its lines must fit in 40 hour-long storage batches, or it is refused with `422 log_batch_spread` |
| Requests per key | 2,400 a minute, then `429 rate_limited` with `retry-after: 10` |
| Line | message 8,000 characters; 64 attributes of up to 1,000 characters |
| Services and attribute keys | 200 services counted by name (more count as `<other>`), 500 attribute keys offered as facets |
| Saved searches, alerts | 50 and 20 per product |

Log-based metrics (charting a numeric attribute) and grouping lines by pattern are not available yet.

## Best practices

- **Log structured attributes, not sentences with values in them.** `logger.info("Order paid", { order_id: 42 })` can be searched with `order_id=42`; `"Order 42 paid"` can only be searched as text. `logger.fmt` gives you both.
- **Name your services.** Set `logsService` (or `OTEL_SERVICE_NAME`) so `service:` filters work.
- **Put the person's id on lines about a person** (`distinct_id`), so their lines show on their profile and are covered by deletion requests.
- **Log inside spans** so lines link to their trace. The SDK loggers do this for you.
- **Keep `debug` off in production** with `logsMinLevel`, and drop noisy lines with `beforeSendLog`, to stay inside your allowance.
- **Don't log secrets.** AppHelm scrubs the common ones, but the safest secret is one you never send.

## Troubleshooting

| Symptom | Likely cause | What to do |
| --- | --- | --- |
| No lines from the browser | Analytics consent hasn't been given | Call `setConsent({ analytics: true })` from your banner |
| `403 scope_denied` | The key has neither `logs:write` nor `events:write` | Use a server key with one of them ([Keys, scopes and environments](https://apphelm.dev/docs/keys-and-environments)) |
| `422 product_required` | The key covers several products and none was named | Send `x-apphelm-product: prd_…` or set the `apphelm.product_id` resource attribute |
| `403 product_scope_denied` | The key is limited to other products (sending, searching, saved searches or alerts) | Use a key for this product, or one for all products |
| `404 product_not_found` | The product isn't in this workspace | Copy the id from Settings → Products |
| `413 payload_too_large` | More than 5 MB in one request | Send smaller batches, or gzip them |
| `415 unsupported_encoding` | A compression other than gzip | Use gzip or none |
| `422 log_batch_spread` | One request mixes lines from more than about 40 hours | Send old lines in separate requests by time |
| `429 log_limit` | The month's log allowance is used | Raise `logsMinLevel`, drop noisy lines, or change plan |
| `429 rate_limited` | Too many requests for one key | Batch more lines per request; the SDKs batch for you |
| Lines show the wrong time | The timestamp was more than 7 days old or 10 minutes ahead | Fix the source clock; the original is in `apphelm.original_timestamp` |
| Lines don't link to traces | No trace id on the line | Log inside a span, or add `trace_id` to JSON lines |
| `debug` lines are missing | The default minimum level is `info` | Set `logsMinLevel: "debug"` (or the SDK's equivalent) |
| A search says "searched back to …" | It stopped early to stay fast | Press **Load older**, or narrow the search with `level:` or `service:` |
