Sentry Logging Integration

Important information if you use Sentry

The Print Button uses Sentry logging for internal telemetry and debugging. If you are also using Sentry there are some things to note in order to avoid conflicts.

The Print Button uses Sentry v7, and we have found that script initialization order matters when running other versions of Sentry. As a library, Sentry relies on a global object that is unversioned. If the Print Button scripts are initialized after your Sentry instance is initialized, it will overwrite other versions of Sentry. Despite best efforts to remedy, this behavior must be changed by the Sentry team.

To avoid conflicts we have tested two methods for initializing Sentry:

  • Using a local sentry object

  • Initializing our package before the host-site version of Sentry

Using a Local Sentry Object

The Sentry recommended best practice for multiple Sentry instances on a page is to use an isolated instance:

let hub: Sentry.Hub
let sentry: Sentry.BrowserClient

function initSentry() {
  sentry = new Sentry.BrowserClient({
    dsn: SENTRY_DSN,
    tracesSampleRate: process.env.NODE_ENV === 'production' ? 0.2 : 1.0,
    stackParser: Sentry.defaultStackParser,
    integrations: [
      new Sentry.Breadcrumbs()
    ],
  })
  hub = new Sentry.Hub()
  hub.bindClient(sentry)
}

and then to export that isolated instance for all logging and breadcrumbs usage like this:

function getSentry(): SentryInstance {
  if (!(hub && sentry) {
    initSentry()
  }
  return {
    sentry,
    hub,
  }
}

export function captureException(err: unknown, context?: Record<string, unknown>): void {
  console.error(err)
  const { sentry } = getSentry()
  const scope = new Sentry.Scope()
  if (context) {
    scope.setContext('context', context)
  }
  sentry.captureException(err, {}, scope)
}

export function addBreadcrumb(crumb: Sentry.Breadcrumb): void {
  const { hub } = getSentry()
  hub.addBreadcrumb(crumb)
}

Now in all places that sentry is required, one can import this module and use the addBreadcrumb and captureException methods.

Using script initialization order

The Print Button uses the method above to ensure access to the Sentry object. Because the Print Button has insulated itself from the global scope, you may feel free to replace the global Sentry object with any version of Sentry your system uses.

To achieve this, make sure the Print Button initialization script runs before your Sentry initialization script. Or if you happen to lazy load the Print Button, immediately after you have initialized our script, reimport the script tag for the version of Sentry you would like to use.

Last updated