56

I have application where some critical issues are reported with console.error but are not thrown so application might continue to run - possibly in crippled state.

It's necessary to report also console.error issues, but Sentry (Raven) library send to server only thrown exceptions.

Does someone knows how to solve this nicely ?

(ideally without need to rewrite all console.error calls, cause also some vendor libraries might still write output just into console)

Jurosh
  • 6,984
  • 7
  • 40
  • 51
  • There is some kind of undocumented console plugin here. https://github.com/getsentry/sentry-javascript/blob/aead4d1c8f194ed5f2de0889dc250a5859976a14/packages/raven-js/plugins/console.js – kumar303 May 24 '19 at 20:06
  • 4
    There is newer documentation for capturing console messages with a plugin: https://docs.sentry.io/platforms/javascript/?platform=browsernpm#captureconsole – kumar303 May 24 '19 at 20:22
  • 1
    Seems to have moved to here https://docs.sentry.io/platforms/javascript/configuration/integrations/plugin/#captureconsole – scipilot Apr 09 '21 at 02:08

6 Answers6

84

As user @kumar303 mentioned in his comment to the question ... you can use the JS console integration Sentry.Integrations.CaptureConsole.

See https://docs.sentry.io/platforms/javascript/configuration/integrations/plugin/#captureconsole for documentation.

At the end you JS code to setup Sentry looks as follows:

import * as Sentry from '@sentry/browser';
import { CaptureConsole } from '@sentry/integrations';

Sentry.init({
  dsn: 'https://your-sentry-server-dsn',
  integrations: [
    new CaptureConsole({
      levels: ['error']
    })
  ],
  release: '1.0.0',
  environment: 'prod',
  maxBreadcrumbs: 50
})

If then someone calls console.error a new event will sent to sentry.

scipilot
  • 6,681
  • 1
  • 46
  • 65
Marc Schmid
  • 1,028
  • 7
  • 13
  • 2
    Can you also send the stack trace with this method? I had a look at the doc and did some tests, but it looks like only the message is sent – Sébastien Tromp Oct 29 '19 at 06:22
  • Haven't tried to get the stack traces with 'Integrations.CaptureConsole'. In our case the 'Breadcrumbs' helped to solve most issues, as previous log messages (also info and debug) could be seen in sentry. – Marc Schmid Nov 04 '19 at 12:31
  • Note: integrations are no default features, but plugin's. It confused me that the documentation mentioned *defaults to ['log', 'info', 'warn', 'error', 'debug', 'assert']* - this is only true after you have added `CaptureConsole` – Advena Jan 19 '23 at 09:31
6

Here's a more robust override solution

// creating function declarations for better stacktraces (otherwise they'd be anonymous function expressions)
var oldConsoleError = console.error;
console.error = reportingConsoleError; // defined via function hoisting
function reportingConsoleError() {
  var args = Array.prototype.slice.call(arguments);
  Sentry.captureException(reduceConsoleArgs(args), { level: 'error' });
  return oldConsoleError.apply(console, args);
};

var oldConsoleWarn = console.warn;
console.warn = reportingConsoleWarn; // defined via function hoisting
function reportingConsoleWarn() {
  var args = Array.prototype.slice.call(arguments);
  Sentry.captureMessage(reduceConsoleArgs(args), { level: 'warning' });
  return oldConsoleWarn.apply(console, args);
}

function reduceConsoleArgs(args) {
  let errorMsg = args[0];
  // Make sure errorMsg is either an error or string.
  // It's therefore best to pass in new Error('msg') instead of just 'msg' since
  // that'll give you a stack trace leading up to the creation of that new Error
  // whereas if you just pass in a plain string 'msg', the stack trace will include
  // reportingConsoleError and reportingConsoleCall
  if (!(errorMsg instanceof Error)) {
    // stringify all args as a new Error (which creates a stack trace)
    errorMsg = new Error(
      args.reduce(function(accumulator, currentValue) {
        return accumulator.toString() + ' ' + currentValue.toString();
      }, '')
    );
  }
  return errorMsg;
}
Liedman
  • 10,099
  • 4
  • 34
  • 36
Devin Rhode
  • 23,026
  • 8
  • 58
  • 72
5

Based on @Marc Schmid's solution I came up with the following working example, if you link to the Sentry CDN files.

<script src="https://browser.sentry-cdn.com/5.11.1/bundle.min.js" integrity="sha384-r7/ZcDRYpWjCNXLUKk3iuyyyEcDJ+o+3M5CqXP5GUGODYbolXewNHAZLYSJ3ZHcV" crossorigin="anonymous"></script>
<!-- https://github.com/getsentry/sentry-javascript/issues/1976#issuecomment-492260648 -->
<script src="https://browser.sentry-cdn.com/5.11.1/captureconsole.min.js"></script>
<script>
    Sentry.init({
        dsn: 'https://abcdef1234567890@sentry.io/012345',
        debug: false,
        integrations: [
            new Sentry.Integrations.CaptureConsole({
                levels: ['error']
            })
        ],
    });
</script>
marcus
  • 699
  • 11
  • 33
4

Found a little hacky solution:

const consoleError = console.error;
console.error = function(firstParam) {
  const response = consoleError.apply(console, arguments);
  Raven.captureException(firstParam, { level: 'error' });
  return response;
};

It just wraps console.error and report each of error logs in console to Raven (Sentry).

If someone have nicer approach (maybe some hidden feature of Sentry) please feel free to share!

akkez
  • 13
  • 3
Jurosh
  • 6,984
  • 7
  • 40
  • 51
2

I wrote a library that is going this using your Sentry instance. https://github.com/aneldev/dyna-sentry

Dennis T
  • 109
  • 4
0

I checked the documentation and as of today, you can also include stack trace by using attachStacktrace: true, so the code would look like this:

<script src="https://browser.sentry-cdn.com/7.49.0/bundle.min.js" crossorigin="anonymous"></script>
<script src="https://browser.sentry-cdn.com/7.49.0/captureconsole.min.js" crossorigin="anonymous"></script>
<script>
    Sentry.init({
        dsn: 'https://abcdef1234567890@sentry.io/012345',
        environment: 'production',
        integrations: [ new Sentry.Integrations.CaptureConsole({ levels: ['error'] }) ],
        attachStacktrace: true,
    });
</script>
UrShulgi
  • 11
  • 3