Sources & ingest
A Source is a stream of logs, metrics or
traces ingested into Better Stack Telemetry. You create one per application or
platform, then hand its token and ingestingHost to whatever sends the data.
Everything is sent to https://<ingestingHost> with
Authorization: Bearer <token>. A source token can only write into that one
source: it reads nothing and manages nothing.
- env
- source token
- retention
- 30 days
- Apiwrites →api-logs
- Production appqueries →api-logs
Create a source
Section titled “Create a source”const logs = yield* BetterStack.Telemetry.Source("api-logs", { platform: "http", logsRetention: 30,});platform decides which integration the source is set up for: its default
transformation, Live tail format and setup guide. http, open_telemetry,
prometheus, aws, gcp, cloudflare_worker and vector are some of them;
the Source reference lists every value.
platform, dataRegion and teamId can’t change: changing one replaces the
source, which deletes its data and issues a new token. Destroying a source
deletes it with its data too. Keep one with Alchemy’s
removal policy
where the data matters.
Hand the token to your code
Section titled “Hand the token to your code”The token is Redacted. Pass it as a secret environment value, never inside a
string that ends up in state:
const env = { BETTERSTACK_SOURCE_TOKEN: logs.token, BETTERSTACK_INGESTING_HOST: logs.ingestingHost,};That record works as a Cloud.Service’s env, a Worker’s environment, or a
Vector or OpenTelemetry Collector configuration.
Export OpenTelemetry from a Service
Section titled “Export OpenTelemetry from a Service”The default path: instrument with Effect itself (named spans with Effect.fn,
span attributes, Effect.logInfo with annotations, Metrics) and provide one
export layer, Telemetry.Export({ source }), on the host’s implementation. It
sends traces, logs and metrics to an open_telemetry source at
https://<ingestingHost>/v1/{traces,logs,metrics} with
Authorization: Bearer <token>, the endpoints
Better Stack’s OpenTelemetry guide
gives. Watching your services and
Part 4 of the tutorial show it end to end.
For an exporter that isn’t Effect’s, such as the Node OpenTelemetry SDK or a
Collector, Telemetry.otlpEnv builds the standard OTEL_EXPORTER_OTLP_*
variables for a source.
When you are not using OpenTelemetry
Section titled “When you are not using OpenTelemetry”These bindings send data without OTLP: JSON log events, metric points, or the host’s Effect log lines.
Send logs from a Service
Section titled “Send logs from a Service”Telemetry.IngestLogs binds a source to a host and gives running code a typed
sender. The host receives the source’s token and ingesting host as
BETTERSTACK_SOURCE_<SOURCE>_TOKEN and …_INGESTING_HOST, and no API token.
Provide IngestLogsHttp on the Service’s implementation:
import * as BetterStack from "betterstack-alchemy";import * as Effect from "effect/Effect";import * as HttpServerResponse from "effect/http/HttpServerResponse";import { AppLogs, Box } from "./shared.ts";
export default class Api extends BetterStack.Cloud.Service<Api>()( "Api", { server: Box, main: import.meta.url, port: 3000 }, Effect.gen(function* () { const logs = yield* BetterStack.Telemetry.IngestLogs(AppLogs); return { fetch: Effect.gen(function* () { yield* logs([{ message: "order placed", orderId: "o-1" }]); return HttpServerResponse.text("ok"); }).pipe(Effect.orDie), }; }).pipe(Effect.provide(BetterStack.Telemetry.IngestLogsHttp)),) {}Pass a list rather than one request per line: every event counts against the team’s log ingestion. The same binding works on a Cloudflare Worker or a Lambda Function, where the token becomes that host’s secret.
Push metrics
Section titled “Push metrics”Telemetry.IngestMetrics does the same for metrics. The source must be a
prometheus source; any other answers Forbidden:
import * as BetterStack from "betterstack-alchemy";import * as Effect from "effect/Effect";import * as HttpServerResponse from "effect/http/HttpServerResponse";import { Box } from "./shared.ts";
export const AppMetrics = BetterStack.Telemetry.Source("AppMetrics", { platform: "prometheus" });
export default class Api extends BetterStack.Cloud.Service<Api>()( "Api", { server: Box, main: import.meta.url, port: 3000 }, Effect.gen(function* () { const metrics = yield* BetterStack.Telemetry.IngestMetrics(AppMetrics); return { fetch: Effect.gen(function* () { yield* metrics({ name: "orders_total", counter: { value: 1 }, tags: { region: "eu" } }); return HttpServerResponse.text("ok"); }).pipe(Effect.orDie), }; }).pipe(Effect.provide(BetterStack.Telemetry.IngestMetricsHttp)),) {}Metrics are billed by distinct series, and every new combination of name and
tags is a new one. Keep tags low-cardinality.
Ship Effect’s logs as JSON events
Section titled “Ship Effect’s logs as JSON events”Telemetry.ShipLogs sends the host’s own Effect.log lines to an http source
in bounded batches, as { dt, level, message, ...annotations } events:
import * as BetterStack from "betterstack-alchemy";import * as Effect from "effect/Effect";import * as HttpServerResponse from "effect/http/HttpServerResponse";import { AppLogs, Box } from "./shared.ts";
export default class Api extends BetterStack.Cloud.Service<Api>()( "Api", { server: Box, main: import.meta.url, port: 3000 }, Effect.gen(function* () { return { fetch: Effect.gen(function* () { yield* Effect.logInfo("order placed").pipe(Effect.annotateLogs({ orderId: "o-1" })); return HttpServerResponse.text("ok"); }), }; }).pipe(Effect.provide(BetterStack.Telemetry.ShipLogs(AppLogs))),) {}ShipLogs takes minimumLevel, batchSize, maxBuffer and window; raise
minimumLevel for chatty services. Pick one log path per host: as ShipLogs’s
documentation in the package states, with alchemy@2.0.0-beta.87, ShipLogs
and the export layer’s OTLP logs on the same host do not combine (each installs
the host’s logger set, and the later one replaces the other’s).
Query the data from running code
Section titled “Query the data from running code”Telemetry.Query runs SQL against a source through Better Stack’s Query API.
Reading needs an API token: there is no read-only per-source credential. You
pass the token explicitly; use a team-scoped Telemetry token:
import * as BetterStack from "betterstack-alchemy";import * as Effect from "effect/Effect";import * as HttpServerResponse from "effect/http/HttpServerResponse";import { AppLogs, Box } from "./shared.ts";
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)),) {}These runtime bindings (IngestLogs, IngestMetrics, ShipLogs,
Export, Query) are tested against the offline mock only; see
Compatibility.
Group sources
Section titled “Group sources”A SourceGroup keeps related sources
together. Deleting the group keeps its sources:
const backend = yield* BetterStack.Telemetry.SourceGroup("backend", { name: "Backend", sortIndex: 1,});yield* BetterStack.Telemetry.Source("checkout", { platform: "open_telemetry", sourceGroupId: backend.id,});Extract metrics from logs
Section titled “Extract metrics from logs”An ExtractedMetric evaluates an SQL
expression for each log line and precomputes aggregations, so dashboards
chart it cheaply. Leave aggregations empty for a label to filter and group
by:
yield* BetterStack.Telemetry.ExtractedMetric("duration", { sourceId: logs.id, name: "duration_ms", sqlExpression: "JSONExtract(raw, 'message_json', 'duration_ms', 'Nullable(Float64)')", aggregations: ["avg", "max", "min"],});Collect from AWS
Section titled “Collect from AWS”An aws source is connected to an AWS account by
SourceAwsAccount, through the IAM
role from Better Stack’s CloudFormation stack.
AwsLogGroupSubscription
subscribes one CloudWatch log group, or keeps one out:
const aws = yield* BetterStack.Telemetry.Source("aws", { platform: "aws" });yield* BetterStack.Telemetry.SourceAwsAccount("aws-account", { sourceId: aws.id, awsRoleArn: yield* Config.Redacted("BETTER_STACK_AWS_ROLE_ARN"), awsExternalId: yield* Config.Redacted("BETTER_STACK_AWS_EXTERNAL_ID"), awsAutoSubLogGroups: true,});yield* BetterStack.Telemetry.AwsLogGroupSubscription("noisy-logs", { sourceId: aws.id, region: "us-east-1", name: "/aws/lambda/noisy", subscribed: false,});SourceAwsAccount has no create or delete: it takes over the source named by
sourceId, and destroying it only forgets it.
Collect from GCP
Section titled “Collect from GCP”SourceGcpProject connects a gcp
source to a Google Cloud project through Workload Identity Federation:
const gcp = yield* BetterStack.Telemetry.Source("gcp", { platform: "gcp" });yield* BetterStack.Telemetry.SourceGcpProject("gcp-project", { sourceId: gcp.id, gcpProjectId: "my-project", gcpProjectNumber: "123456789012", gcpLogFilter: 'severity >= "WARNING"',});Query from outside: connections
Section titled “Query from outside: connections”A Connection issues credentials for
querying ingested data with ClickHouse over HTTP, or as a Grafana data source:
const sql = yield* BetterStack.Telemetry.Connection("analytics", { clientType: "clickhouse", teamIds: ["t123"], ipAllowlist: ["203.0.113.0/24"], validUntil: null, note: "Analytics notebooks",});Every change replaces the connection and issues new credentials. Without
validUntil the credential expires one hour after it’s created; null never
expires. Creating connections needs a global API token.
Where next
Section titled “Where next”- Collectors: an agent on your hosts that creates its own source.
- Dashboards and Alerts: what reads a source.
- Watching your services: a source next to a monitor, heartbeat and error tracking.
- Reference:
Source,SourceGroup,ExtractedMetric,Connection, lookups. - Better Stack: Sources (API), HTTP ingestion, OpenTelemetry.