Telemetry.Query
Query a Source’s data from running code with the Query API
(Telemetry.query): SELECT dt, raw FROM {{source}} WHERE … over a
time window, the rows back as JSON.
Credential. Reading data needs an API token: Better Stack has no
read-only, per-source credential (a source token can only write). The
host therefore receives the ApiToken you pass — explicitly, never
the deployer’s own — under the name you give it (plus <name>_TEAM_ID
when given), and the source’s id. That token can do everything it can do
in the Telemetry API, not only query this source, so use a team-scoped
Telemetry API token (Settings → API tokens), never a global one when you
can avoid it. The SQL itself is scoped to the bound source by
{{source}}.
Cost. Queries over long ranges read many rows; the API refuses or
windows oversized ones unless raw: true.
Provide QueryHttp on the host’s implementation.
Querying from a Cloud.Service
Section titled “Querying from a Cloud.Service”The last errors, on demand
const QueryToken = BetterStack.apiTokenFromConfig("BETTERSTACK_TELEMETRY_QUERY_TOKEN");
export default class Api extends BetterStack.Cloud.Service<Api>()( "Api", { server: Box, main: import.meta.url, port: 3000 }, Effect.gen(function* () { const query = yield* BetterStack.Telemetry.Query(AppLogs, QueryToken); return { fetch: Effect.gen(function* () { const result = yield* query({ query: "SELECT dt, raw FROM {{source}} WHERE level = 'error' ORDER BY dt DESC LIMIT 10", startTime: "now-1h", }); return yield* HttpServerResponse.json(result.data?.attributes?.rows ?? []); }).pipe(Effect.orDie), }; }).pipe(Effect.provide(BetterStack.Telemetry.QueryHttp)),) {}Works the same on any Alchemy host (Worker, Lambda): the token is bound
through RuntimeContext as a secret.