Observability

Tracing

Distributed tracing with W3C Trace Context and B3 headers, per-request server spans, child spans and downstream propagation.

2 min readUpdated DocumentationEdit this page
On this page4

Usage

TypeScript
TS
1import { Tracer } from '@axiljs/observability'
2
3const tracer = new Tracer({ serviceName: 'my-api' })
4
5await tracer.trace('user.create', async (span) => {
6  span.setAttribute('user.email', email)
7  return await createUser(data)
8})

trace(name, fn, parentSpan?) ends the span when fn settles, sets its status to ok or error, and hands it to the exporter. Without an exporter option, finished spans are kept in memory (last 10,000) and returned by tracer.getSpans().

TypeScript
TS
1const tracer = new Tracer({
2  serviceName: 'my-api',
3  exporter: (span) => sendToCollector(span)  // SpanData
4})

Propagation

tracer.extractContext(headers) reads a W3C traceparent header (falling back to Zipkin B3 x-b3-traceid / x-b3-spanid). tracer.injectContext(span) returns the headers to send downstream: traceparent, x-b3-traceid and x-b3-spanid.

Per-request server spans

With a tracer, observabilityMiddleware starts an http.request span for every request, continuing the caller's trace when a valid traceparent (or B3) header is present (propagate: true by default). It writes the trace headers to the response and ends and exports the span when the response finishes.

Note

New in 0.3.3: the server span is exposed to later middleware and handlers:

  • req.locals.span (the Span), req.locals.tracer and req.locals.traceContext ({ traceId, spanId })
  • getRequestSpan(req) and getTraceContext(req) helpers, which return undefined when no tracer is configured

Child spans and downstream calls

TypeScript
TS
1import { Application } from '@axiljs/core'
2import {
3  Tracer,
4  observabilityMiddleware,
5  getRequestSpan,
6  getTraceContext
7} from '@axiljs/observability'
8
9const app = new Application()
10const tracer = new Tracer({ serviceName: 'orders-api' })
11
12app.use(observabilityMiddleware({ tracer }))
13
14app.get('/orders/:id', async (req, res) => {
15  const parent = getRequestSpan(req)
16
17  // Child span of the server span; ended and exported by trace()
18  const order = await tracer.trace('db.order.find', async (span) => {
19    span.setAttribute('order.id', req.params.id)
20    return db.orders.find(req.params.id)
21  }, parent)
22
23  // Propagate the trace to another service
24  const call = parent ? parent.startChild('http.inventory') : tracer.startSpan('http.inventory')
25  const stock = await fetch(`http://inventory/items/${order.itemId}`, {
26    headers: tracer.injectContext(call)   // traceparent + B3 headers
27  }).then(r => r.json())
28  tracer.exportSpan(call.setStatus('ok').end())
29
30  // Correlate logs with the trace
31  logger.info('Order fetched', { ...getTraceContext(req) })
32
33  res.success({ order, stock })
34})

Tip

tracer.startSpan(name, { parent }) accepts either a Span or a { traceId, spanId } context, so startSpan('job', { parent: getTraceContext(req) }) also continues the request's trace.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY