如何使用Sentry报告控制台错误?

56

我有一个应用程序,其中一些关键问题是使用 console.error 报告的,但并没有被 thrown ,因此应用程序可能会继续运行 - 可能处于瘫痪状态。

需要报告 console.error 问题,但 Sentry(Raven)库只向服务器发送抛出的异常。

是否有人知道如何优雅地解决这个问题?

(最好不需要重写所有 console.error 调用,因为某些供应商库仍然可能将输出写入控制台)


这里有一种未记录的控制台插件。https://github.com/getsentry/sentry-javascript/blob/aead4d1c8f194ed5f2de0889dc250a5859976a14/packages/raven-js/plugins/console.js - kumar303
4
有一个新的插件文档可以用来捕获控制台消息:https://docs.sentry.io/platforms/javascript/?platform=browsernpm#captureconsole。请注意,要保持原意不变,同时使语言更加通俗易懂。 - kumar303
1
似乎已经移动到这里 https://docs.sentry.io/platforms/javascript/configuration/integrations/plugin/#captureconsole - scipilot
6个回答

85
如用户@kumar303在他对问题的评论中提到...你可以使用JS控制台集成Sentry.Integrations.CaptureConsole。
请参阅文档
最后,设置Sentry的JS代码如下所示:
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
})

如果有人调用console.error,将会发送一个新的事件到Sentry。

2
你能否也发送这个方法的堆栈跟踪?我查看了文档并进行了一些测试,但似乎只有消息被发送。 - Sébastien Tromp
尚未尝试使用“Integrations.CaptureConsole”获取堆栈跟踪。在我们的情况下,“Breadcrumbs”有助于解决大多数问题,因为可以在Sentry中看到先前的日志消息(也包括信息和调试)。 - Marc Schmid
注意:集成不是默认功能,而是插件。文档提到的 defaults to ['log', 'info', 'warn', 'error', 'debug', 'assert'] 让我感到困惑 - 只有在添加了 CaptureConsole 后才是真的。 - Advena

6

这是一个更加强大的覆盖解决方案

// 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;
}

5

在@Marc Schmid的解决方案基础上,如果您链接到Sentry CDN文件,则我提供了以下工作示例。

<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>

这个功能能提供可读的堆栈跟踪以便定位错误吗? - iuliu.net

4
发现了一个小技巧解决方案:
const consoleError = console.error;
console.error = function(firstParam) {
  const response = consoleError.apply(console, arguments);
  Raven.captureException(firstParam, { level: 'error' });
  return response;
};

它只是对console.error进行了封装,并将每个错误日志报告给Raven(Sentry)控制台。
如果有更好的方法(也许是Sentry的一些隐藏功能),请随意分享!

2

0

我查看了文档,截至今天,您也可以使用 attachStacktrace: true 来包含堆栈跟踪,因此代码将如下所示:

<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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接