Documentation

SDKs/AdonisJS

Custom Tracing

Add your own spans, attributes, and events with helpers and decorators

Auto-instrumentation covers HTTP, database, Redis, and more. Use these helpers to trace your own business logic: a report generation, a payment flow, a slow third-party SDK.

Create a span with record()

Use record() to wrap a section of code in a span. This is useful when you want to measure the duration of a specific operation that is not automatically instrumented.

app/services/report_service.ts
import { record } from '@monocle.sh/adonisjs-agent/helpers'

const report = await record('report.generate', async (span) => {
  span.setAttributes({ 'report.type': 'monthly', 'report.userId': userId })

  const data = await fetchReportData(userId)
  return generatePdf(data)
})

record() handles both sync and async callbacks, automatically records exceptions, and closes the span when done.

Decorators

The @span() decorator wraps a single method in a span. The @spanAll() decorator wraps every public method in a class.

app/services/order_service.ts
import { inject } from '@adonisjs/core'
import { span, spanAll } from '@monocle.sh/adonisjs-agent/decorators'

// Wrap a single method
export class OrderService {
  @span()
  async findById(id: string) {
    return Order.findOrFail(id)
  }

  @span({ name: 'order.create', attributes: { operation: 'create' } })
  async create(data: CreateOrderData) {
    return Order.create(data)
  }
}

// Or wrap all methods at once
@spanAll({ prefix: 'user' })
export class UserService {
  async findById(id: string) {
    /* span: user.findById */
  }
  async create(data: UserData) {
    /* span: user.create */
  }
}

Attributes, events, and context propagation

TypeScript
import {
  getCurrentSpan,
  setAttributes,
  recordEvent,
  injectTraceContext,
  extractTraceContext,
} from '@monocle.sh/adonisjs-agent/helpers'

// Get the current active span
const span = getCurrentSpan()

// Add attributes to the current span
setAttributes({ 'order.total': 99.99, 'order.currency': 'EUR' })

// Record an event on the current span
recordEvent('order.confirmed', { orderId: '123' })

// Distributed tracing: inject context into outgoing headers
const headers = {}
injectTraceContext(headers)

// Distributed tracing: extract context from incoming headers
const context = extractTraceContext(request.headers)

Always import helpers from @monocle.sh/adonisjs-agent rather than @adonisjs/otel. Monocle's versions attach source code context and the full Error.cause chain to recorded exceptions.

Search documentation

Search pages and sections of the Monocle documentation