@plan-fi/logger
v0.3.0
Published
OTLP logging client for newlog. Batches logs and propagates W3C trace context across services.
Maintainers
Readme
@plan-fi/logger
OTLP logging client for newlog. Batches log records, propagates W3C trace context across services, and times units of work so latency is attributable.
Zero dependencies. Works in Cloudflare Workers, Node 18+, Deno, and browsers (never ship an ingest token to a browser — see Security).
npm install @plan-fi/loggerQuick start
import { createLogger } from '@plan-fi/logger'
// Adopt the inbound trace, or start a new one if there isn't one.
const log = createLogger(
{
endpoint: 'https://ingest.holdequity.com',
token: env.NEWLOG_TOKEN,
app: 'planfi',
surface: 'rest', // rest | mcp | web | scraper | llm
env: env.ENVIRONMENT, // prod | stage | dev | local
onError: (err, dropped) => reportToSentry(err, { dropped }),
},
request.headers,
)
log.info('resolving household', { 'household.id': id })
// Propagate AND time the hop. See `tracedFetch` below.
const res = await log.tracedFetch(mcpUrl, { method: 'POST' }, {
eventName: 'tool.call',
route: '/tools/:name',
})
ctx.waitUntil(log.flush()) // see "Flushing" — this is mandatoryFlushing is mandatory in a Worker
The SDK buffers and flushes on a timer. That timer does not fire once the
response has returned and the isolate goes idle. Any handler that buffers fewer
than batchSize (default 100) records loses them unless you flush explicitly.
ctx.waitUntil(log.flush()) // every request path. Not an optimization.Flushing the root logger drains records written by child spans too — they
share one buffer. (Before 0.3.0 a child span had its own buffer, so
ctx.waitUntil(log.flush()) silently dropped every tracedFetch and
startClientSpan record.)
flush() never throws — telemetry must not take down the thing it observes. It
also never fails silently: a permanently rejected batch (a bad token, a malformed
payload) calls onError, and falls back to console.error if you didn't provide
one. Transient 5xx and 429 responses are retried with exponential backoff
(maxRetries, default 3). A 4xx is not retried — it will never succeed.
tracedFetch — propagation and timing in one call
The two things everyone forgets on an outbound call: passing traceparent, and
timing it as a CLIENT span. Without the first, a request crossing services
produces two disconnected traces. Without the second, latency is attributed to
you rather than to the service you called.
const res = await log.tracedFetch(mcpUrl, { method: 'POST', body }, {
eventName: 'tool.call',
route: '/tools/:name', // the TEMPLATE, never the concrete path
})Returns the Response untouched, preserves your headers, rethrows network
errors, and records span_kind=client, duration_ms, route, and
status_code. A 5xx closes the span at error severity automatically.
Timing work: duration_ms and CLIENT spans
p95 duration by event_name is only answerable if durations are recorded. Wrap
the unit of work in a span:
const span = log.startClientSpan('tool.call') // spanKind: 'client'
try {
const res = await fetch(toolUrl, { headers: { traceparent: span.traceparent } })
span.end({ 'tool.name': name }) // records wall-time as duration_ms
} catch (err) {
span.fail(err) // records duration AND the error
}end() and fail() are idempotent — a double-close (a finally plus an explicit
call on the happy path) would otherwise emit a second, longer measurement and
skew every percentile upward.
Then:
GET /api/stats?groupBy=eventName&spanKinds=client&from=…&to=…
→ { buckets: [{ key: "tool.call", count, p50, p95, p99, … }], truncated }Only records with a measured duration participate. An untimed log line is not a zero-millisecond operation.
Writing under an existing span: bindLogger
createLogger always mints a new child span beneath the inbound
traceparent. That is correct at a service boundary, and wrong everywhere else.
If you already have a tracer and want to emit the same event to newlog under
the same span — dual-writing during a migration, or adapting an existing
LogSink — use bindLogger, which adopts a span verbatim and mints nothing:
import { bindLogger, adoptTraceparent } from '@plan-fi/logger'
const span = adoptTraceparent(request.headers.get('traceparent')) // parse, don't mint
const log = bindLogger(opts, span) // writes under `span.spanId` exactly
log.info('turn.start', {}, { eventName: 'turn.start', spanKind: 'server' })Routing a dual-write through createLogger would write the event under a fresh
child S' while the old sink writes it under S. The two span trees would never
line up — and comparing them is the entire point of dual-writing before cutover.
Backfilling historical data
log() stamps ts: Date.now() unless you override it. For a port, pass the
original event time:
log.info(body, attrs, { ts: originalEpochMs, eventName, spanKind, durationMs })The ingest stores ts verbatim — no clamp, no skew window — and records server
time separately as observedTs.
⚠️ The hot tier prunes on event time (ts < now - 72h), so records older than
72 hours are accepted and then deleted within ~15 minutes unless the cold tier is
enabled. For bulk imports use scripts/backfill.mjs in the newlog repo, which
refuses to send them rather than letting the import silently evaporate.
API
| Export | Purpose |
|---|---|
| createLogger(opts, incoming?, kind?) | Adopt inbound traceparent, mint a child span |
| bindLogger(opts, span, kind?) | Write under an existing span, verbatim |
| adoptTraceparent(header) | Parse a traceparent into a SpanContext without minting |
| logger.child(kind?) | Nested span in this process |
| logger.startSpan(name, kind?) / startClientSpan(name) | Timed unit of work |
| logger.tracedFetch(input, init?, opts?) | fetch + traceparent + CLIENT span timing |
| span.end(attrs?) / span.fail(err, attrs?) | Close, recording duration_ms |
| logger.traceparent | Header for the next hop |
| logger.flush() | Ship the buffer. Hand to ctx.waitUntil. |
Levels: trace debug info warn error. error() accepts an Error and
lifts the stack into attributes rather than the body.
Per-record LogOptions: { ts, eventName, spanKind, durationMs, route, statusCode, span }.
route must be the matched template (/plan/:id), not the concrete path —
grouping by the path makes every request its own bucket. statusCode and
durationMs are omitted, not zeroed, when they don't apply: 0 is a real
duration and not a real status.
Security
The token grants write access to your log stream. Keep it in a secret store. Never ship it to a browser — anything in browser JavaScript is readable by any visitor. Log from your backend instead.
Tokens are issued per producer, so a leaked one is revoked without rotating the others.
