Robert Lemiesz
Robert Lemiesz

Reputation: 1156

Is there anyway to push javascript console logs to sentry

I am using the console.error() console.warn() in man places in my app to track failing code. Is there anyway to automatically log these to Sentry. https://sentry.io.

It is a react app, and it seems the componentDidCatch() method they suggest only catches exceptions.

Upvotes: 4

Views: 5223

Answers (3)

limco
limco

Reputation: 1420

In case this helps anyone, use Sentry's CaptureConsole integration for this: Sentry.Integrations.CaptureConsole

Official Documentation: https://docs.sentry.io/platforms/javascript/configuration/integrations/plugin/#captureconsole

Refer to this post: How to report console.error with Sentry?

Example Code:

import { CaptureConsole as CaptureConsoleIntegration } from "@sentry/integrations";

Sentry.init({
  dsn: 'https://your-sentry-server-dsn',
  debug: true, // If `true`, Sentry will try to print out useful debugging information if something goes wrong with sending the event. Set it to `false` in production
  integrations: [new CaptureConsoleIntegration(
    {
      // array of methods that should be captured
      // defaults to ['log', 'info', 'warn', 'error', 'debug', 'assert']
      levels: ['log', 'info', 'warn', 'error', 'debug', 'assert']
    }
  )]
});

Upvotes: 5

AJStacy
AJStacy

Reputation: 5233

The selected answer to this question is generally an anti-pattern. You never want to override a standard API within the browser because other code implementations within your application might expect the behavior to be a specific way and it could cause bugs. Also, future developers contributing to your codebase might not be aware that you are hijacking the standard and end up using it incorrectly.

Take a look at an open source project I've created specifically for solving these types of problems: https://adzejs.com

With Adze you can create log listeners that will fire whenever a specific log at your target level is fired. You can then fire events to Sentry from the listener.

Upvotes: 0

PSK
PSK

Reputation: 17943

One way of doing this is to overwrite the console.error and console.warn with your own custom implementation, so whenever any part of the code calls the console.error or console.warn the call will be intercepted by your custom function where you can perform the required action on it.

Following example shows a custom implementation of console.error method.

//Store the original reference of console.error
var orgError = console.error;
//Overwirte the default function
console.error = function(error) {
  //All error will be intercepted here
  alert("Intercepted -> " + error);
  //Invoke the original console.error to show the message in console
  return orgError(error);
}
try {
  //Following line will throw error
  nonExistentFunction();
} catch (error) {
  console.error(error);
}

Upvotes: 1

Related Questions