Use sentry #4599
-
Hi, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey @rutonyru! 👋🏻 There is no need to use a dedicated library to use Sentry with AdonisJS. Here is an example I have in production. It is a middleware that is executed to encapsulate the request and send telemetry information about it to Sentry (if you activate it inside Sentry). import * as Sentry from '@sentry/node';
import type { HttpContext } from '@adonisjs/core/http';
import type { NextFn } from '@adonisjs/core/types/http';
export default class MonitoringMiddleware {
async handle(ctx: HttpContext, next: NextFn) {
const client = Sentry.getClient();
const scope = new Sentry.Scope();
scope.setClient(client);
scope.setTag('url', ctx.request.url());
ctx.sentry = scope;
await Sentry.startSpan(
{
name: ctx.routeKey!,
op: 'http.server',
scope,
},
async () => {
await next();
},
);
}
}
declare module '@adonisjs/core/http' {
export interface HttpContext {
sentry: Sentry.Scope
}
} It also adds Feel free to also add it inside the container binding. ctx.containerResolver.bindValue(Sentry, sentry) Allowing you to inject the Sentry instance inside any of your services. Here is the provider that configures Sentry: import * as Sentry from '@sentry/node';
import { nodeProfilingIntegration } from '@sentry/profiling-node';
import type { ApplicationService } from '@adonisjs/core/types';
export default class MonitoringProvider {
constructor(protected app: ApplicationService) {}
async boot() {
if (this.app.inProduction) {
const config = this.app.config.get<any>('sentry', {});
Sentry.init({
dsn: config.dsn,
environment: config.environment,
release: config.release,
integrations: [nodeProfilingIntegration()],
tracesSampleRate: 0.2,
profilesSampleRate: 0.2,
});
}
}
} You can change the exception handler to add Sentry there too, so it can catch all your errors. export default class HttpExceptionHandler extends ExceptionHandler {
async report(error: unknown, ctx: HttpContext) {
if (this.shouldReport(error) && app.inDev) {
console.error(error)
return
}
if (!this.shouldReport(error) || !app.inProduction) {
return
}
ctx.sentry.setExtra('error', JSON.stringify(error))
ctx.sentry.captureException(error)
return super.report(error, ctx);
}
} |
Beta Was this translation helpful? Give feedback.
Hey @rutonyru! 👋🏻
There is no need to use a dedicated library to use Sentry with AdonisJS.
You can directly install their SDK and start working from there.
Here is an example I have in production. It is a middleware that is executed to encapsulate the request and send telemetry information about it to Sentry (if you activate it inside Sentry).