Install the Monocle agent in your AdonisJS application
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.
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.
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.
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.
Copy
import type { NextFn } from "@adonisjs/core/types/http";import type { HttpContext } from "@adonisjs/core/http";import { Monocle } from "@monocle.sh/adonisjs-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.
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.