Skip to main content
This guide covers how to install and configure the Monocle agent in your AdonisJS application. You’ll learn how to set up automatic instrumentation, configure user context, and track exceptions.

Prerequisites

  • AdonisJS 6.2.0+ or AdonisJS 7.0.0+
  • A Monocle account with an API key (get one here)

Installation

Install and configure the package using the following command:
node ace add @monocle-app/agent
This command:
  1. Creates config/monocle.ts configuration file
  2. Creates otel.ts initialization file at project root
  3. Adds the otel.ts import as the first import in bin/server.ts
  4. Registers the Monocle provider in adonisrc.ts
  5. Registers the Monocle middleware as the first router middleware
  6. Adds required environment variables to .env and start/env.ts
After running the command, add your API key to .env:
MONOCLE_API_KEY=mk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
You can find your API key in the Monocle dashboard settings. That’s it. Your application now has automatic tracing for HTTP requests, database queries, Redis operations, and more.
The import order is criticalOpenTelemetry must initialize before any other code loads. The SDK needs to patch libraries like http, pg, and redis before they’re imported. That’s why otel.ts is imported as the very first line in bin/server.ts.If you move or remove the import '../otel.js' line, auto-instrumentation will not work.

Environment Variables

The agent requires these environment variables:
VariableDescriptionRequired
MONOCLE_API_KEYYour Monocle API keyYes
APP_NAMEService name for identification in MonocleYes
APP_VERSIONService version (e.g., git sha, semver)Yes
APP_ENVEnvironment: development, staging, or productionYes
The APP_ENV variable determines which environment your telemetry data is associated with in Monocle. You can filter traces, logs, and metrics by environment using the environment selector in the Monocle dashboard.

Configuration

The configuration file is located at config/monocle.ts:
import { defineConfig } from '@monocle-app/agent'
import env from '#start/env'

export default defineConfig({
  apiKey: env.get('MONOCLE_API_KEY'),
  serviceName: env.get('APP_NAME'),
  serviceVersion: env.get('APP_VERSION'),
  environment: env.get('APP_ENV'),
})

Configuration Options

import { defineConfig } from '@monocle-app/agent'
import env from '#start/env'

export default defineConfig({
  // Required: Your Monocle API key
  apiKey: env.get('MONOCLE_API_KEY'),

  // Service identification
  serviceName: env.get('APP_NAME'),
  serviceVersion: env.get('APP_VERSION'),
  environment: env.get('APP_ENV'),

  // Host metrics collection (CPU, Memory, Network, etc.)
  // Set to false to disable
  hostMetrics: {
    enabled: true,
  },

  // CLI command tracing
  cli: {
    enabled: false,
    exclude: ['make:*', 'generate:*', 'queue:work', 'queue:listen'],
  },

  // Trace batching configuration
  batch: {
    maxExportBatchSize: 512,
    scheduledDelayMillis: 5000,
  },

  // Enable gzip compression (default: true)
  compression: true,
})

Customizing Instrumentations

You can configure individual OpenTelemetry instrumentations:
import { defineConfig } from '@monocle-app/agent'

export default defineConfig({
  apiKey: env.get('MONOCLE_API_KEY'),
  serviceName: env.get('APP_NAME'),

  instrumentations: {
    // Add custom ignored URLs
    '@opentelemetry/instrumentation-http': {
      ignoredUrls: ['/internal/*', '/api/ping'],
    },

    // Disable a specific instrumentation
    '@opentelemetry/instrumentation-pg': { enabled: false },
  },
})

User Context

To associate telemetry data with authenticated users, use Monocle.setUser() in your authentication middleware. This allows you to filter traces and exceptions by user in the Monocle dashboard.
import type { NextFn } from '@adonisjs/core/types/http'
import type { HttpContext } from '@adonisjs/core/http'
import { Monocle } from '@monocle-app/agent'

export default class SilentAuthMiddleware {
  async handle(ctx: HttpContext, next: NextFn) {
    await ctx.auth.check()

    if (ctx.auth.user) {
      Monocle.setUser({
        id: ctx.auth.user.id,
        email: ctx.auth.user.email,
        // Add any custom attributes
        plan: ctx.auth.user.plan,
        tenantId: ctx.auth.user.tenantId,
      })
    }

    return next()
  }
}
Be careful not to include sensitive data (passwords, tokens, API keys) in user attributes. These values are sent to Monocle and will be visible in trace viewers.

Exception Tracking

Exceptions are automatically recorded in spans when thrown during a request. The agent hooks into AdonisJS’s ExceptionHandler.report() method to capture exceptions with their stack traces.

Manual Exception Capture

If you want to manually capture exceptions in custom code:
import { Monocle } from '@monocle-app/agent'

try {
  // your code
} catch (error) {
  Monocle.captureException(error, {
    user: { id: '123', email: '[email protected]' },
    tags: { component: 'payment' },
    extra: { orderId: 456 },
  })
  throw error
}

CLI Command Tracing

You can optionally trace Ace CLI commands. This is disabled by default.
import { defineConfig } from '@monocle-app/agent'

export default defineConfig({
  // ...

  cli: {
    enabled: true,
    // Include specific commands (supports glob patterns)
    include: ['migration:*', 'db:*'],
    // Exclude specific commands
    exclude: ['make:*', 'generate:*', 'queue:work', 'queue:listen'],
  },
})

Disabling Telemetry

If no API key is provided, telemetry is automatically disabled. This is useful for local development without sending data to Monocle.
# .env.development
MONOCLE_API_KEY=