How to use @bugsnag/core - 10 common examples

To help you get started, we’ve selected a few @bugsnag/core examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github bugsnag / bugsnag-js / packages / browser / src / config.js View on Github external
const { schema } = require('@bugsnag/core/config')
const { map } = require('@bugsnag/core/lib/es-utils')
const { stringWithLength } = require('@bugsnag/core/lib/validators')

module.exports = {
  releaseStage: {
    defaultValue: () => {
      if (/^localhost(:\d+)?$/.test(window.location.host)) return 'development'
      return 'production'
    },
    message: 'should be set',
    validate: stringWithLength
  },
  logger: {
    ...schema.logger,
    defaultValue: () =>
      // set logger based on browser capability
      (typeof console !== 'undefined' && typeof console.debug === 'function')
        ? getPrefixedConsole()
        : undefined
  }
}

const getPrefixedConsole = () => {
  const logger = {}
  const consoleLog = console.log
  map(['debug', 'info', 'warn', 'error'], (method) => {
    const consoleMethod = console[method]
    logger[method] = typeof consoleMethod === 'function'
      ? consoleMethod.bind(console, '[bugsnag]')
      : consoleLog.bind(console, '[bugsnag]')
github bugsnag / bugsnag-js / packages / plugin-console-breadcrumbs / console-breadcrumbs.js View on Github external
exports.init = (client) => {
  const isDev = /^dev(elopment)?$/.test(client.config.releaseStage)

  const explicitlyDisabled = client.config.consoleBreadcrumbsEnabled === false
  const implicitlyDisabled = (client.config.autoBreadcrumbs === false || isDev) && client.config.consoleBreadcrumbsEnabled !== true
  if (explicitlyDisabled || implicitlyDisabled) return

  map(CONSOLE_LOG_METHODS, method => {
    const original = console[method]
    console[method] = (...args) => {
      client.leaveBreadcrumb('Console output', reduce(args, (accum, arg, i) => {
        // do the best/simplest stringification of each argument
        let stringified = '[Unknown value]'
        // this may fail if the input is:
        // - an object whose [[Prototype]] is null (no toString)
        // - an object with a broken toString or @@toPrimitive implementation
        try { stringified = String(arg) } catch (e) {}
        // if it stringifies to [object Object] attempt to JSON stringify
        if (stringified === '[object Object]') {
          // catch stringify errors and fallback to [object Object]
          try { stringified = JSON.stringify(arg) } catch (e) {}
        }
        accum[`[${i}]`] = stringified
        return accum
github bugsnag / bugsnag-js / packages / plugin-inline-script-content / inline-script-content.js View on Github external
const addSurroundingCode = lineNumber => {
      // get whatever html has rendered at this point
      if (!DOMContentLoaded || !html) html = getHtml()
      // simulate the raw html
      const htmlLines = [ '' ].concat(html.split('\n'))
      const zeroBasedLine = lineNumber - 1
      const start = Math.max(zeroBasedLine - 3, 0)
      const end = Math.min(zeroBasedLine + 3, htmlLines.length)
      return reduce(htmlLines.slice(start, end), (accum, line, i) => {
        accum[start + 1 + i] = line.length <= MAX_LINE_LENGTH ? line : line.substr(0, MAX_LINE_LENGTH)
        return accum
      }, {})
    }
github bugsnag / bugsnag-js / packages / expo / src / config.js View on Github external
const { reduce } = require('@bugsnag/core/lib/es-utils')
const Constants = require('expo-constants').default

// If the developer property is not present in the manifest, it means the app is
// not connected to a development tool and is either a published app running in
// the Expo client, or a standalone app (we also assume production for a missing
// manifest, but that should never happen)
const IS_PRODUCTION = !Constants.manifest || !Constants.manifest.developer

// The app can still run in production "mode" in development environments, in which
// cases the global boolean __DEV__ will be set to true
const IS_PRODUCTION_MODE = typeof __DEV__ === 'undefined' || __DEV__ !== true

module.exports = {
  logger: {
    ...schema.logger,
    defaultValue: () => getPrefixedConsole()
  },
  releaseStage: {
    ...schema.releaseStage,
    defaultValue: () => {
      if (IS_PRODUCTION) return 'production'
      if (IS_PRODUCTION_MODE) return 'local-prod'
      return 'local-dev'
    }
  }
}

const getPrefixedConsole = () => {
  return reduce([ 'debug', 'info', 'warn', 'error' ], (accum, method) => {
    // console.error causes standalone expo apps to reload on android
    // so don't do any logging that level – use console.warn instead
github bugsnag / bugsnag-js / packages / expo / src / config.js View on Github external
// not connected to a development tool and is either a published app running in
// the Expo client, or a standalone app (we also assume production for a missing
// manifest, but that should never happen)
const IS_PRODUCTION = !Constants.manifest || !Constants.manifest.developer

// The app can still run in production "mode" in development environments, in which
// cases the global boolean __DEV__ will be set to true
const IS_PRODUCTION_MODE = typeof __DEV__ === 'undefined' || __DEV__ !== true

module.exports = {
  logger: {
    ...schema.logger,
    defaultValue: () => getPrefixedConsole()
  },
  releaseStage: {
    ...schema.releaseStage,
    defaultValue: () => {
      if (IS_PRODUCTION) return 'production'
      if (IS_PRODUCTION_MODE) return 'local-prod'
      return 'local-dev'
    }
  }
}

const getPrefixedConsole = () => {
  return reduce([ 'debug', 'info', 'warn', 'error' ], (accum, method) => {
    // console.error causes standalone expo apps to reload on android
    // so don't do any logging that level – use console.warn instead
    const consoleMethod = (IS_PRODUCTION && method === 'error') ? console.warn : console[method]
    accum[method] = consoleMethod.bind(console, '[bugsnag]')
    return accum
  }, {})
github bugsnag / bugsnag-js / packages / plugin-inline-script-content / inline-script-content.js View on Github external
client.config.beforeSend.unshift(report => {
      // remove any of our own frames that may be part the stack this
      // happens before the inline script check as it happens for all errors
      report.stacktrace = filter(report.stacktrace, f => !(/__trace__$/.test(f.method)))

      const frame = report.stacktrace[0]

      // if frame.file exists and is not the original location of the page, this can't be an inline script
      if (frame && frame.file && frame.file.replace(/#.*$/, '') !== originalLocation.replace(/#.*$/, '')) return

      // grab the last script known to have run
      const currentScript = getCurrentScript()
      if (currentScript) {
        const content = currentScript.innerHTML
        report.updateMetaData(
          'script',
          'content',
          content.length <= MAX_SCRIPT_LENGTH ? content : content.substr(0, MAX_SCRIPT_LENGTH)
        )
      }
github bugsnag / bugsnag-js / packages / plugin-network-breadcrumbs / network-breadcrumbs.js View on Github external
function handleXHRError () {
  if (includes(getIgnoredUrls, this[REQUEST_URL_KEY])) {
    // don't leave a network breadcrumb from bugsnag notify calls
    return
  }
  // failed to contact server
  client.leaveBreadcrumb('XMLHttpRequest error', {
    request: `${this[REQUEST_METHOD_KEY]} ${this[REQUEST_URL_KEY]}`
  }, BREADCRUMB_TYPE)
}
github bugsnag / bugsnag-js / packages / plugin-network-breadcrumbs / network-breadcrumbs.js View on Github external
function handleXHRLoad () {
  if (includes(getIgnoredUrls(), this[REQUEST_URL_KEY])) {
    // don't leave a network breadcrumb from bugsnag notify calls
    return
  }
  const metadata = {
    status: this.status,
    request: `${this[REQUEST_METHOD_KEY]} ${this[REQUEST_URL_KEY]}`
  }
  if (this.status >= 400) {
    // contacted server but got an error response
    client.leaveBreadcrumb('XMLHttpRequest failed', metadata, BREADCRUMB_TYPE)
  } else {
    client.leaveBreadcrumb('XMLHttpRequest succeeded', metadata, BREADCRUMB_TYPE)
  }
}
github bugsnag / bugsnag-js / packages / plugin-server-session / session.js View on Github external
const sendSessionSummary = client => sessionCounts => {
  const releaseStage = inferReleaseStage(client)

  // exit early if the reports should not be sent on the current releaseStage
  if (isArray(client.config.notifyReleaseStages) && !includes(client.config.notifyReleaseStages, releaseStage)) {
    client._logger.warn(`Session not sent due to releaseStage/notifyReleaseStages configuration`)
    return
  }

  if (!client.config.endpoints.sessions) {
    client._logger.warn(`Session not sent due to missing endpoints.sessions configuration`)
    return
  }

  if (!sessionCounts.length) return

  const backoff = new Backoff({ min: 1000, max: 10000 })
  const maxAttempts = 10
  req(handleRes)

  function handleRes (err) {
github bugsnag / bugsnag-js / packages / plugin-browser-session / session.js View on Github external
startSession: client => {
    const sessionClient = client
    sessionClient._session = new client.BugsnagSession()

    const releaseStage = inferReleaseStage(sessionClient)

    // exit early if the reports should not be sent on the current releaseStage
    if (isArray(sessionClient.config.notifyReleaseStages) && !includes(sessionClient.config.notifyReleaseStages, releaseStage)) {
      sessionClient._logger.warn(`Session not sent due to releaseStage/notifyReleaseStages configuration`)
      return sessionClient
    }

    if (!sessionClient.config.endpoints.sessions) {
      sessionClient._logger.warn(`Session not sent due to missing endpoints.sessions configuration`)
      return sessionClient
    }

    sessionClient._delivery.sendSession({
      notifier: sessionClient.notifier,
      device: sessionClient.device,
      app: { ...{ releaseStage }, ...sessionClient.app },
      sessions: [
        {
          id: sessionClient._session.id,