A NestJS module for Sentry with support for error reporting and operation tracing.
To install this package, you must have a reference to the @geekbears
repository on your npmrc
.
Run the following command to install the NestJS module along with the required dependencies
npm install --save @geekbears/gb-nest-sentry @sentry/node @sentry/tracing
Once installed, configure the module provider on your application's root module:
GbNestModule.forRoot({
dsn: '<dsn>',
environment: '<env>',
...
}),
Alternatively, an async factory can be used:
GbNestModule.forRootAsync({
inject: [],
useFactory: () => ({
dsn: '<dsn>',
environment: '<env>',
...
}),
}),
The module uses the default NodeOptions
interface exposed by @sentry/node
to configure the Sentry instance.
For more details regarding supported options, please refer to the Sentry Documentation.
The module itself sets up a span for every operation, and database tracing can be configured by adding the corresponding integration to the configuration options. For example, a Mongoose connection can be traced by defining the following integration
on the config object:
import {Integrations} from '@sentry/node';
...
GbNestModule.forRoot({
integrations: [new Integrations.Mongo({ useMongoose: true })]
}),
For more details regarding database tracing, please refer to the Sentry Documentation
Additionally, manual tracing can be integrated by injecting the SentryService
and then creating a new child span. The developer must ensure to handle the child span appropriately.
- Import the injection decorator
import { InjectSentry } from '@geekbears/gb-nest-sentry';
- Inject the service wherever you need it
constructor(@InjectSentry() private readonly sentryService: SentryService) {}
- Start a new child span
this.sentryService.startChild({ ... })
Geekbears projects rely on NestJS's ConfigService
and environment variables, by leveraging these features we can optimally integrate Sentry with the following configuration:
GbSentryModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
dsn: config.get<string>('SENTRY_DSN'),
environment: config.get<string>('NODE_ENV'),
enabled: config.get('SENTRY_ENABLED') === 'true' ? true : false,
tracesSampleRate: 1.0,
integrations: [new Integrations.Mongo({ useMongoose: true })],
// debug: true,
}),
}),
Explanation:
- The factorye requires injecting the
ConfigService
so every value can be read from environment variables. - The
dsn
andenvironment
fields are mandatory. - The
enabled
flag is a useful way to reduce noise by ignoring certain environments or configs (such as testing on development). - Integrate Mongo tracing with the
useMongoose
flag
- The current implementation for the
SentryService
uses aREQUEST
scope. An improvement is already underway to support other contexts appart from HTTP