Logs

OpenTelemetry logs on client and server with zero configuration. Errors, navigations, failed loaders and every server request are logged without a line of code; you add the business events.

log in page and component scripts

Import log from 'pragma' in any page, component or store script and call debug, info, warn or error from an action or mount(). Keep the message short and fixed and put the variable parts in attributes named like OpenTelemetry's (order.id, exception.message), so records group and filter cleanly.

The runtime adds url.path, a timestamp and the page's traceId, queues the record and posts batches to /_otel. In pragma dev every call also prints to the browser console, and the dev server prints each received record as a JSON line in the terminal. debug stays in the console: the client sends info and above.

routes/examples/logs/_components/order-log/order-log.html

<script>  import { log } from 'pragma'  import { flush } from '../../../../../core/log.js'  const severityNumbers = { debug: 5, info: 9, warn: 13, error: 17 }  let records = []  let orderNumber = 1041  let nextRecordId = 1  const orderId = () => 'A-' + orderNumber  const recordRows = () => records.map(entry => ({    ...entry,    levelText: entry.level.toUpperCase() + ' ' + severityNumbers[entry.level],    isInfo: entry.level === 'info',    isWarn: entry.level === 'warn',    isError: entry.level === 'error',    attributesText: JSON.stringify(entry.attributes),  }))  function record(level, body, attributes) {    log[level](body, attributes)    records = [{ id: nextRecordId, level, body, attributes }, ...records].slice(0, 4)    nextRecordId += 1  }  function placeOrder() {    orderNumber += 1    record('info', 'order placed', { 'order.id': orderId(), 'order.items': 3 })  }  function retryPayment() {    record('warn', 'payment retried', { 'order.id': orderId(), 'payment.attempt': 2 })  }  function failPayment() {    try {      throw new Error('card declined')    } catch (failure) {      record('error', 'payment failed', { 'order.id': orderId(), 'exception.message': failure.message })    }  }  function sendNow() {    flush()  }  function mount() {    log.debug('order panel mounted')  }</script><div class="grid w-full max-w-lg gap-4">  <div class="flex flex-wrap gap-2" role="group" aria-label="Order events">    <button type="button" class="btn btn-small" @click="placeOrder">Place order</button>    <button type="button" class="btn btn-small" @click="retryPayment">Retry payment</button>    <button type="button" class="btn btn-small" @click="failPayment">Fail payment</button>  </div>  <ol class="flex min-h-48 flex-col border-t border-line font-mono text-xs" aria-label="Last records passed to log">    <for record in $recordRows key=record.id>      <li class="record grid gap-x-3 gap-y-1 border-b border-line py-2.5">        <span class="tabular-nums" .text-accent="record.isInfo" .text-warning-300="record.isWarn" .text-danger-300="record.isError">{record.levelText}</span>        <span class="text-ink">{record.body}</span>        <span class="record-attributes break-all text-faint">{record.attributesText}</span>      </li>    </for>    <empty>      <li class="py-3 font-sans text-sm text-faint">No records yet. Click a button.</li>    </empty>  </ol>  <div class="flex flex-wrap items-center justify-between gap-3">    <p class="max-w-sm text-sm text-faint">Queued, then posted to /_otel every 2 s or at 50 records, and with sendBeacon when the tab hides.</p>    <button type="button" class="btn btn-small" @click="sendNow">Send now</button>  </div></div><style>  .record {    grid-template-columns: 5.5rem 1fr;    animation: record-in 0.35s var(--ease-out);  }  .record-attributes { grid-column: 2; }  @keyframes record-in { from { opacity: 0; translate: 0 -0.25rem; } }  @media (prefers-reduced-motion: reduce) {    .record { animation: none; }  }</style>

Live result

Queued, then posted to /_otel every 2 s or at 50 records, and with sendBeacon when the tab hides.

The list shows the last calls this component made; open the network panel to see the batched POST /_otel, or press Send now.

What is logged without asking

An action that throws or rejects is not swallowed: the error reaches window, and the runtime logs it as ERROR with exception.type, exception.message and exception.stacktrace. The same goes for any uncaught error or unhandled rejection on the page. Do not wrap code in try/catch only to log it again.

  • navigation (info): every client navigation, with pragma.route, push or pop, and duration_ms.
  • navigation failed and loader failed (error): a page module or a load request that failed.
  • A traceparent header on every runtime fetch (/_data, /_action), so server records join the client trace.
  • On the server, one record per request: GET /orders with method, route, status and duration in seconds; ERROR for 5xx.

routes/examples/logs/_components/auto-capture/auto-capture.html

<script>  let failures = []  let nextFailureId = 1  function remember(kind, message) {    failures = [{ id: nextFailureId, kind, message }, ...failures].slice(0, 4)    nextFailureId += 1  }  function throwNow() {    throw new Error('inventory sync crashed')  }  async function rejectLater() {    await new Promise(resolve => setTimeout(resolve, 150))    throw new Error('price refresh timed out')  }  function mount() {    const onError = event => remember('error', event.message)    const onRejection = event => remember('unhandledrejection', event.reason?.message ?? String(event.reason))    addEventListener('error', onError)    addEventListener('unhandledrejection', onRejection)    return () => {      removeEventListener('error', onError)      removeEventListener('unhandledrejection', onRejection)    }  }</script><div>  <div class="auto-capture-actions" role="group" aria-label="Failures">    <button type="button" class="btn btn-small" @click="throwNow">Throw in an action</button>    <button type="button" class="btn btn-small" @click="rejectLater">Reject in an async action</button>  </div>  <ol class="auto-capture-events" aria-label="Uncaught errors, each one logged by the runtime">    <for failure in $failures key=failure.id>      <li class="auto-capture-event">        <span class="auto-capture-kind">{failure.kind}</span>        <span class="auto-capture-message">{failure.message}</span>      </li>    </for>    <empty>      <li class="auto-capture-empty">No uncaught errors yet. Neither action has a try/catch or a log call.</li>    </empty>  </ol></div><style>  [data-c="auto-capture"] { display: grid; gap: 1rem; width: min(100%, 34rem); }  .auto-capture-actions { display: flex; flex-wrap: wrap; gap: 0.5rem; }  .auto-capture-events { display: grid; min-height: 9rem; align-content: start; border-top: 1px solid var(--color-line); }  .auto-capture-event {    display: grid;    grid-template-columns: 9.5rem 1fr;    gap: 0.75rem;    padding: 0.625rem 0;    border-bottom: 1px solid var(--color-line);    font-family: var(--font-mono);    font-size: 0.75rem;  }  .auto-capture-kind { color: var(--color-danger-300); }  .auto-capture-message { color: var(--color-ink); overflow-wrap: anywhere; }  .auto-capture-empty { padding: 0.75rem 0; color: var(--color-faint); font-size: 0.875rem; }  @media (max-width: 30rem) {    .auto-capture-event { grid-template-columns: 1fr; gap: 0.125rem; }  }</style>

Live result

  1. No uncaught errors yet. Neither action has a try/catch or a log call.
Each button fails on purpose. The list reads the same window events the runtime listens to; the console shows the logged errors in dev.

log in load and server actions

load and every server action receive log in their argument. Its records carry the request's traceId and spanId, taken from the client's traceparent. A server action that throws is logged with its stack, answers 500, and call() rejects with the message on the client. pragma dev also prints server log.debug; in production it is off unless PRAGMA_LOG_LEVEL=debug.

routes/examples/logs/demo/refund.html

<title>Refund demo · pragma examples</title><meta name="robots" content="noindex"><script>  import { data, call, log } from 'pragma'  let sending = false  let error = ''  async function send(actionName) {    sending = true    error = ''    try {      data.refund.status = (await call(actionName, { id: data.refund.id })).status    } catch (failure) {      log.error('refund action failed', { 'refund.action': actionName, 'exception.message': failure.message })      error = failure.message    } finally {      sending = false    }  }</script><c-demo-page>  <h1 class="font-mono text-sm text-muted">Refund queue</h1>  <if page.loading>    <div class="skeleton h-28" aria-busy="true" aria-label="Loading refund"></div>  </if>  <else-if page.error>    <p class="font-mono text-sm text-danger-300" role="alert">{page.error.message}</p>  </else-if>  <else>    <article class="grid gap-4 border border-line bg-surface p-5" aria-labelledby="refund-title">      <div class="flex flex-wrap items-baseline justify-between gap-3">        <h2 id="refund-title" class="font-mono text-base">{data.refund.customer}</h2>        <p class="font-mono text-xs uppercase tracking-wide text-faint">{data.refund.status}</p>      </div>      <p class="font-mono text-2xl tabular-nums">{data.refund.amount}</p>      <div class="flex flex-wrap gap-2">        <button type="button" class="btn btn-small btn-primary" @click="send('approve')" :disabled="$sending">Approve</button>        <button type="button" class="btn btn-small" @click="send('escalate')" :disabled="$sending">Escalate</button>        <button type="button" class="btn btn-small" @click="send('reopen')" :disabled="$sending">Reopen</button>      </div>      <if $error>        <p class="font-mono text-xs text-danger-300" role="alert">{$error}</p>      </if>    </article>  </else></c-demo-page>

routes/examples/logs/demo/refund.server.js

const refundStatus = new Map([['R-1042', 'pending']])export async function load({ log }) {  log.info('refund queue loaded', { 'refund.count': refundStatus.size })  return { refund: { id: 'R-1042', customer: 'Order A-1042', amount: '€38.00', status: refundStatus.get('R-1042') } }}export const actions = {  async approve({ input, log }) {    refundStatus.set(input.id, 'approved')    log.info('refund approved', { 'refund.id': input.id })    return { status: 'approved' }  },  async escalate({ input, log }) {    log.warn('refund escalation requested', { 'refund.id': input.id })    throw new Error('escalation service unavailable')  },  async reopen({ input }) {    refundStatus.set(input.id, 'pending')    return { status: 'pending' }  },}

Live result

/examples/logs/demo/refund

A real route with load and three server actions. Approve logs info, Escalate logs a warning and then throws.

Without a collector the records go to stdout, one JSON line each. This is the Node server's real output for the demo, built in a fresh app named shop: the load request, Approve and Escalate.

node dist/server/node.mjs
{"timeUnixNano":"1795054520700000000","severityNumber":9,"severityText":"INFO","body":"refund queue loaded","attributes":{"refund.count":1},"traceId":"4bf92f3577b34da6a3ce929d0e0e4736","spanId":"bd014b0e913de49d","resource":{"service.name":"shop"}}
{"timeUnixNano":"1795054520702000000","severityNumber":9,"severityText":"INFO","body":"GET /admin/refund","attributes":{"http.request.method":"GET","url.path":"/_data/admin/refund","http.response.status_code":200,"http.server.request.duration":0.004170464999999922,"http.route":"/admin/refund"},"traceId":"4bf92f3577b34da6a3ce929d0e0e4736","spanId":"bd014b0e913de49d","resource":{"service.name":"shop"}}
{"timeUnixNano":"1795054520716000000","severityNumber":9,"severityText":"INFO","body":"refund approved","attributes":{"refund.id":"R-1042"},"traceId":"4bf92f3577b34da6a3ce929d0e0e4736","spanId":"483e4d9314e8dfd2","resource":{"service.name":"shop"}}
{"timeUnixNano":"1795054520716000000","severityNumber":9,"severityText":"INFO","body":"POST /admin/refund","attributes":{"http.request.method":"POST","url.path":"/_action/admin/refund/approve","http.response.status_code":200,"http.server.request.duration":0.001449903000000063,"http.route":"/admin/refund"},"traceId":"4bf92f3577b34da6a3ce929d0e0e4736","spanId":"483e4d9314e8dfd2","resource":{"service.name":"shop"}}
{"timeUnixNano":"1795054520726000000","severityNumber":13,"severityText":"WARN","body":"refund escalation requested","attributes":{"refund.id":"R-1042"},"traceId":"80b06b4be553162063e0c9cab8037faf","spanId":"ce83d19ad2b0560d","resource":{"service.name":"shop"}}
{"timeUnixNano":"1795054520726000000","severityNumber":17,"severityText":"ERROR","body":"escalation service unavailable","attributes":{"exception.type":"Error","exception.message":"escalation service unavailable","exception.stacktrace":"Error: escalation service unavailable\n    at Object.escalate (file:///…/dist/server/routes/admin/refund.server.js:16:11)\n    …"},"traceId":"80b06b4be553162063e0c9cab8037faf","spanId":"ce83d19ad2b0560d","resource":{"service.name":"shop"}}
{"timeUnixNano":"1795054520726000000","severityNumber":17,"severityText":"ERROR","body":"POST /admin/refund","attributes":{"http.request.method":"POST","url.path":"/_action/admin/refund/escalate","http.response.status_code":500,"http.server.request.duration":0.0011812830000001214,"http.route":"/admin/refund","error.type":"500"},"traceId":"80b06b4be553162063e0c9cab8037faf","spanId":"ce83d19ad2b0560d","resource":{"service.name":"shop"}}

The first three records share one traceId because those requests sent a traceparent; the escalate request was sent without one, so the server started a new trace. Paths in the stack trace are shortened.

Logging from utils/

The services from 'pragma' belong to page, component and store scripts. A plain module in utils/ imports the same client logger from core/log.js; its records join the same batches and the same trace.

utils/currency.js
import { log } from '../core/log.js'

const euro = new Intl.NumberFormat('en-IE', { style: 'currency', currency: 'EUR' })

export function formatPrice(cents) {
  if (!Number.isInteger(cents)) log.warn('price is not in cents', { 'price.value': String(cents) })
  return euro.format(cents / 100)
}

Where the records go

Client batches and server records meet at the server: /_otel accepts batches up to 256 KB and forwards them with the server's own records. Everything is configured with the standard OpenTelemetry environment variables, so any OTLP/HTTP collector works.

OTEL_EXPORTER_OTLP_ENDPOINT
Base URL of an OTLP/HTTP collector. Records go to /v1/logs as OTLP JSON. Unset: one JSON line per record on stdout.
OTEL_EXPORTER_OTLP_LOGS_ENDPOINT
Full logs URL; wins over the base endpoint.
OTEL_EXPORTER_OTLP_HEADERS
Comma-separated key=value pairs sent to the collector, for an API key.
OTEL_SERVICE_NAME
Server service.name. Default: name from pragma.json. Client batches use the page hostname.
OTEL_RESOURCE_ATTRIBUTES
Extra resource attributes, deployment.environment=prod,service.version=1.4.0.
PRAGMA_LOG_LEVEL
Server minimum level: debug, info, warn or error. Default info in production; pragma dev sets debug, so server log.debug shows up while developing.
production
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel.example.com OTEL_EXPORTER_OTLP_HEADERS=x-api-key=secret node dist/server/node.mjs

Never log passwords, tokens, cookies, emails or other personal data, never log inside loops or on every keystroke, and never use console.*: pragma check rejects it with js/console. On a static host there is no /_otel: the client stops sending after the first 404 or 405, while pragma serve always accepts it.