wolas:sentry
This package is a wrapper for sentry library. It allows you to simply use latest Sentry SDK on both client and a server in your meteor application.
This package is MIT Licensed.
Requirements
- 2.x: Meteor 3.0 or newer (Sentry SDK 11 needs Node 20.19 or newer).
- Meteor 2: stay on 1.x.
Installation
meteor add wolas:sentry
Upgrading from 1.x to 2.x
2.x ships Sentry SDK 11. Read the Sentry migration guide for the full list. The changes most likely to affect you:
- More data collected by default.
sendDefaultPiiis replaced bydataCollection, and leaving it unset now collects user info, cookies, request bodies and database queries. To keep the old, stricter behaviour, passdataCollectiontoLogger.init(see the guide). - Stack traces on messages.
attachStacktracenow defaults totrue, soLogger.info('...')and friends carry a stack trace. Issue grouping may change. PassattachStacktrace: falseto opt out. - Unhandled server exceptions are now reported by Sentry's own handler, as
fataland unhandled. The server process still exits, as before. info,debugandlogcalls no longer reach Sentry by default. They still runpostprocess. To keep sending them, passlevelstoLogger.init(see Choosing which levels reach Sentry).Logger.critical()is sent asfatal, because Sentry 11 has nocriticallevel. Alert rules that matchedcriticalneed to matchfatal.
Usage
The same interface can be used on a client and server.
Initialization (client/server)
import Logger from 'meteor/wolas:sentry'; Logger.init({ dsn: YOUR_SENTRY_DSN GOES HERE //any other options you want to pass to sentry init function });
Release (client/server)
Every event carries a release, so Sentry can tell which deploy an issue came from. The first one found wins:
- the
releaseoption passed toLogger.init - on the server, the
SENTRY_RELEASEenvironment variable; on either side, a release a Sentry bundler plugin injected Meteor.gitCommitHash, the commit the app was built from
When none is set, events go out without a release. Meteor.gitCommitHash is undefined when the app isn't built from a git checkout.
Logger.init({ dsn, release: 'my-app@1.4.0' });
Logging events (client/server)
import Logger from 'meteor/wolas:sentry'; Logger.warning('Something happened', { userId: getUserId() });
Logger has methods for all Sentry severity levels, such as:
Logger.error() Logger.fatal() Logger.warning() Logger.log() Logger.info() Logger.debug() Logger.critical()
Sentry has no critical level, so Logger.critical() reaches Sentry as fatal. postprocess still receives critical.
each method has following signature:
function ( event, extra )
Returns: string \ undefined - sentry event id, or undefined when the level is not sent.
| Param | Type | Description |
|---|---|---|
| event | Error \ string | event that is being logged |
| extra | object | any extra params you want to pass |
Every event a Logger method sends carries a key tag, client or server, naming the side that logged it; filter on key in Sentry to separate the two. Logger.init throws if levels is not an array or names a level other than fatal, error, warning, log, info, debug or critical, so a bad list fails at init instead of silently dropping events.
Choosing which levels reach Sentry (client/server)
By default only fatal, error, warning and critical are sent. Other levels still run postprocess, so you can keep them in your console without paying for them in Sentry. A level that is not sent returns undefined instead of an event id.
Pass levels to choose your own list:
Logger.init({ dsn: YOUR_SENTRY_DSN GOES HERE, levels: ['fatal', 'error', 'warning', 'critical', 'info'] });
This only applies to Logger calls. Events Sentry captures by itself, such as unhandled exceptions, are always sent. Use Sentry's beforeSend to filter those.
Logging unhandled exceptions (client/server)
Any unhandled exceptions that happen on the client or server should be automatically logged to Sentry. Nothing to configure there.
Server context (server)
Every Logger call on the server, and every error captureMethodErrors reports, is tagged with what was running at the time, with no extra code:
meteor.method- the name of the Meteor method, ormeteor.publication- the name of the publication,user.id- the id of the user who called it, when someone is logged in.
Events logged outside any method or publication, for example in Meteor.startup or a timer, carry none of these and look exactly as before. So do events Sentry captures by itself, such as unhandled exceptions.
Reporting method errors (server)
Meteor catches an error thrown inside a method and sends it to the client, so Sentry never sees it. Turn on captureMethodErrors to report it:
Logger.init({ dsn: YOUR_SENTRY_DSN GOES HERE, captureMethodErrors: true });
Each error is reported once, with the same method tag and user as above, then rethrown unchanged, so the client gets exactly what it got before. It works for sync and async methods, registered before or after Logger.init.
Errors that are instanceof Meteor.Error, or that have isClientSafe: true, are not reported. Meteor sends both to the client as the method's intended answer, such as a validation failure or a permission denial, not a crash.
Pass false to turn it off, also after an earlier Logger.init.
Tracing methods (server)
Sentry's own instrumentation sees HTTP and database calls, but not Meteor methods. Turn on traceMethods to get a span per method run:
Logger.init({ dsn: YOUR_SENTRY_DSN GOES HERE, tracesSampleRate: 0.1, traceMethods: true });
It needs tracesSampleRate (or tracesSampler): without one, Sentry records no spans and nothing is sent.
- The span is named after the method, with op
meteor.method. - It carries the method name as
meteor.methodand the caller asuser.id, like the errors above. A call with no logged-in user carries no user. - With Sentry's default span streaming,
meteor.methodis a span attribute. WithtraceLifecycle: 'static'it is also a tag on the transaction. - Each method run is its own transaction, even when another span is active, such as the HTTP request a DDP connection rides on.
- Sentry's own MongoDB and HTTP spans nest under it, when Sentry's instrumentation is active in your app.
- Method arguments are never recorded, as they can hold passwords.
- It works for sync and async methods, registered before or after
Logger.init. What the method returns or throws is unchanged. - A
Meteor.ErrororisClientSafeerror does not mark the span failed, as it is the method's intended answer. Any other thrown error does.
Pass false to turn it off, also after an earlier Logger.init.
Tracing publications (server)
Turn on tracePublications to get a span per publication handler run:
Logger.init({ dsn: YOUR_SENTRY_DSN GOES HERE, tracesSampleRate: 0.1, tracePublications: true });
Like traceMethods, it needs tracesSampleRate (or tracesSampler).
- The span covers the handler run only, until it returns or its promise settles. It does not cover the subscription's lifetime.
- The span is named after the publication, with op
meteor.publication. It carries the publication name asmeteor.publicationand the subscriber asuser.id. A subscription with no logged-in user carries no user. As with methods,meteor.publicationis a span attribute under span streaming, and also a tag withtraceLifecycle: 'static'. - A universal publication (
Meteor.publish(null, ...)) has no name. Its span is namedmeteor.publication (universal), carries the attributemeteor.publication.universal: trueand nometeor.publicationtag, like errors logged inside one. - Each run is its own transaction, even when another span is active. Sentry's own MongoDB and HTTP spans nest under it, when Sentry's instrumentation is active in your app.
- Subscription arguments are never recorded, as they can hold tokens.
- It works for publications registered before or after
Logger.init, by name, as an object or universal. What the handler returns or throws is unchanged. Any thrown error marks the span failed, aMeteor.Errorincluded.
Pass false to turn it off, also after an earlier Logger.init.
Client options (client)
Logger.init({ dsn: YOUR_SENTRY_DSN GOES HERE, trackUsers: true, methodBreadcrumbs: true, subscriptionBreadcrumbs: true, traceMethods: false });
trackUsers(defaulttrue) - attaches the signed-in user's email to every event. Needsaccounts-base.methodBreadcrumbs(defaulttrue) - adds ameteor.methodbreadcrumb named after eachMeteor.call,Meteor.callAsync,Meteor.applyandMeteor.applyAsync, so an event shows which methods ran before it. Method arguments are never included, as they can hold passwords. Passfalseto turn it off, also after an earlierLogger.init. Its companion for subscriptions issubscriptionBreadcrumbs.subscriptionBreadcrumbs(defaulttrue) - adds ameteor.subscriptionbreadcrumb named after eachMeteor.subscribeandMeteor.connection.subscribe, so an event inside a template or hook shows which subscriptions were opened before it. Subscription arguments are never included, as they can hold tokens. Passfalseto turn it off, also after an earlierLogger.init.traceMethods(defaultfalse) - starts a span perMeteor.call,Meteor.callAsync,Meteor.applyandMeteor.applyAsync, beside the breadcrumb. It needstracesSampleRate(ortracesSampler): without one, Sentry records no spans and nothing is sent.- The span is named after the method, with op
meteor.methodand the method name as themeteor.methodtag. Method arguments are never recorded. Meteor.callAsyncandMeteor.applyAsyncwithout a callback end their span when the promise they return settles: the round trip forcallAsync(and forapplyAsyncwithreturnServerResultPromise: true). The promise is the one Meteor returned, with itsstubPromiseandserverPromise.- A call with a callback,
Meteor.applyAsyncincluded, ends its span when the callback fires, so it covers the round trip. - A call with no callback ends its span when
Meteor.callorMeteor.applyreturns. Meteor never hands the caller that result, so the span covers the client-side dispatch only. - Every error marks the span failed, a
Meteor.Errorincluded: on the client a server crash arrives as aMeteor.Errortoo. A stub that throws synchronously marks it failed as well, and the error reaches you unchanged. - It carries the same user
trackUserssets. - Each call is its own transaction, even under the pageload or navigation span of
browserTracingIntegration. - Pass
falseto turn it off, also after an earlierLogger.init. With bothtraceMethodsandmethodBreadcrumbsoff,Meteor.applyandMeteor.applyAsyncare restored.
- The span is named after the method, with op
The client transaction and the server transaction for the same call (see traceMethods on the server) are not linked. DDP carries no headers, so there is nowhere to put a sentry-trace value without changing the method's arguments. An app that needs the link can pass the client's trace id as an explicit method argument and read it on the server itself. This package does not do that.
Postprocessing (client/server)
If you wish to postprocess an event somehow - for instance log it to the console, you can pass a custom function in initialization.
import Logger from 'meteor/wolas:sentry'; Logger.init({ dsn: YOUR_SENTRY_DSN GOES HERE, postprocess: function(level, event, extra) { console.log(`[${level}] - ${event}`, extra); } });
A postprocess hook that throws never breaks the logging call: the call still returns what it would have returned for that level (the event id, or undefined for a level that is not sent), and the hook's error is written to console.error.
Using the Sentry SDK directly (client/server)
For anything the Logger does not wrap, Logger.Sentry is the Sentry SDK this package loads and initialises - @sentry/browser on the client, @sentry/node on the server. It is the same object before and after Logger.init, with every top-level SDK function on it (setTag, setContext, withScope, addBreadcrumb, startSpan, flush, captureMessage, getClient, ...). It is also available as import { Sentry } from 'meteor/wolas:sentry'. The client the SDK created is Logger.Sentry.getClient(), which is also what Logger.init returns.
On the client, session replay, the feedback widget and browser profiling are left out since 3.0: replayIntegration, replayCanvasIntegration, getReplay, feedbackIntegration, feedbackAsyncIntegration, feedbackSyncIntegration, getFeedback, sendFeedback, browserProfilingIntegration and uiProfiler are not on Logger.Sentry. Meteor bundles a package's npm modules whole, without tree shaking, so the full @sentry/browser 11 put 1.1 MiB into every app's initial page load. The package now ships its own build of the SDK with only the code the remaining functions use, and those three features were half of it.
On the client:
import Logger from 'meteor/wolas:sentry'; Logger.init({ dsn: YOUR_SENTRY_DSN GOES HERE }); Logger.Sentry.setTag('tenant', tenantId);
On the server, for instance to send pending events before the process exits:
import Logger from 'meteor/wolas:sentry'; await Logger.Sentry.flush(2000);
Logger.init must stay the only place Sentry.init is called. Do not call Logger.Sentry.init, and do not add @sentry/browser or @sentry/node to your app - that would load a second SDK beside this one.
Development
Tests run on the server and in headless Chromium:
npm install npx playwright install chromium npm test
The client's SDK, lib/vendor/sentry-browser.js, is generated from the @sentry/browser in package.json devDependencies. That version must equal @sentry/node in package.js, and the build fails otherwise. After changing either, or the exports left out in scripts/build-client-sdk.mjs, rebuild and commit the result:
npm run build:client-sdk
CI rebuilds it and fails when the result differs from the committed file.
Dependabot only sees the dev tooling in package-lock.json, not the Sentry packages Meteor locks in .npm/package/npm-shrinkwrap.json or the ones bundled into the client SDK, which the build lists in scripts/client-sdk-packages.json. CI checks both on every push and nightly:
npm run audit:runtime
Advisories that cannot affect this package go in scripts/runtime-audit-allowlist.json with a reason and an expiry date.
Commits
Commit messages follow the conventional format, type(scope): subject, for example fix(client): clear the Sentry user on logout. npm install installs a husky commit-msg hook that runs commitlint with @commitlint/config-conventional, and it rejects any other message. The accepted types are build, chore, ci, docs, feat, fix, perf, refactor, revert, style and test.
The type decides the next release: feat is a minor release; fix, perf, docs, chore, refactor and a revert are a patch; build, ci, style and test release nothing on their own. A BREAKING CHANGE: footer makes a major release whatever the type. The ! shorthand (feat!:) passes commitlint but the release tooling does not read it, so a breaking commit needs the footer as well.
Releasing
Releases are cut by hand on master with npm run release, which runs semantic-release. Its config sets ci: false, which only lets it run outside CI; it does not stop a CI run. CI does not release because no job in .circleci/config.yml runs npm run release, so do not add one. It needs push access to master; there is no GitHub plugin and no token.
A run reads the commits since the last tag, writes the release notes to CHANGELOG.md, bumps version in package.json (nothing is published to npm, npmPublish: false), then commits and tags the result.
package.js carries the Atmosphere version, and semantic-release does not touch it or include it in the release commit. Bump it before the release, so the tag carries it: npx semantic-release --dry-run prints the next version, set package.js to that and commit it, then run npm run release, then publish to Atmosphere with meteor publish.
meteor publish is safe to run beside the dev node_modules, because .meteorignore hides everything except lib/ and tests/. A new top-level folder the package loads must be added to it.