客户端 javascript 的错误日志记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11257330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:34:28  来源:igfitidea点击:

Error-logging for javascript on client side

javascriptjqueryerror-handlingstack-trace

提问by shershen

My project which contains a lot of pages with forms. This is a backend of banking CRM system, so any error during working process is to be captured and investigated. On the server side we have enhanced java exceptions system, but if error occurs on client side - javascript the only info we now get is an js-error window in IE or sometimes a screenshot of page made by advanced user.

我的项目包含很多带有表单的页面。这是银行CRM系统的后端,因此工作过程中的任何错误都将被捕获和调查。在服务器端,我们增强了 Java 异常系统,但如果客户端发生错误 - javascript,我们现在获得的唯一信息是 IE 中的 js 错误窗口,或者有时是高级用户制作的页面截图。

Javascript code contains both Jquery-powered UI extensions and hard-coded inline event handlers and functions.

Javascript 代码包含 Jquery 驱动的 UI 扩展和硬编码的内联事件处理程序和函数。

So I am asking whether any approach for capturing js-errors of any kind could be used? some additional library or something that could give me a stacktrace like firebug in Mozilla or web-console in Chrome?

所以我问是否可以使用任何方法来捕获任何类型的 js 错误?一些额外的库或可以给我一个堆栈跟踪的东西,比如 Mozilla 中的 firebug 或 Chrome 中的网络控制台?

回答by voithos

Look into window.onerror. If you want to capture any errors, and report them to the server, then you could try an AJAX request, perhaps.

调查一下window.onerror。如果您想捕获任何错误,并将它们报告给服务器,那么您也许可以尝试 AJAX 请求。

window.onerror = function(errorMessage, errorUrl, errorLine) {
    jQuery.ajax({
        type: 'POST',
        url: 'jserror.jsf',
        data: {
            msg: errorMessage,
            url: errorUrl,
            line: errorLine
        },
        success: function() {
            if (console && console.log) {
                console.log('JS error report successful.');
            }
        },
        error: function() {
            if (console && console.error) {
                console.error('JS error report submission failed!');
            }
        }
    });

    // Prevent firing of default error handler.
    return true;
}

回答by David Cramer

Disclaimer: I'm CEO and creator of Sentry, an open source and paid service which does crash reporting for many languages, including Javascript.

免责声明:我是Sentry 的CEO 和创建者,Sentry是一种开源和付费服务,可为多种语言(包括 Javascript)提供崩溃报告。

It can be pretty challenging to capture frontend exceptions. Technology has gotten better (browser JS engines), but there's still a lot of limitations.

捕获前端异常可能非常具有挑战性。技术已经变得更好(浏览器 JS 引擎),但仍然存在很多限制。

  1. You're going to need a server-side logging endpoint. This has a few complexities as it's possible to abuse it (i.e. PEN testers may try to expose vulnerabilities in it). You also need to deal with CORS here. I'd obviously recommend Sentry for this, as we're best in class, and if you want you can host the server yourself (as its open source).
  2. The implementation of actually capturing the errors in your code is pretty complicated. You cant rely on window.onerrorfor various reasons (mostly because browsers historically give bad information here). What we do in the raven.jsclient (which is based on TraceKit) is patch a number of functions to wrap them in try/catch statements. For example, window.setTimeout. With this we're able to install error handlers that will generate full stacktraces in most browsers.
  3. You'll want to ensure you're generating sourcemaps for your code, and that the server handling the data supports them. Sentry does this both by scraping them automatically (via the standards) or allowing you to upload them via an API. Without this, assuming you're minifying code, things become almost unusable.
  4. The last major issue is noise. Most browser extensions will inject directly into your scripts so you need to filter out the noise. We solve this in two ways: a blacklist of patterns to ignore (i.e. "Script error." being the most useless), as well as a whitelist of domains to accept (i.e. "example.com"). We've found the combination of the two being effective-enough at removing most random noise.
  1. 您将需要一个服务器端日志记录端点。这有一些复杂性,因为它可能被滥用(即 PEN 测试人员可能会尝试暴露其中的漏洞)。您还需要在这里处理 CORS。我显然为此推荐 Sentry,因为我们是同类中最好的,而且如果您愿意,您可以自己托管服务器(作为其开源)。
  2. 实际捕获代码中的错误的实现非常复杂。window.onerror由于各种原因,您不能依赖(主要是因为浏览器历来会在这里提供错误信息)。我们在raven.js客户端(基于 TraceKit)中所做的是修补许多函数以将它们包装在 try/catch 语句中。例如,window.setTimeout。有了这个,我们就可以安装错误处理程序,在大多数浏览器中生成完整的堆栈跟踪。
  3. 您需要确保为代码生成源映射,并且处理数据的服务器支持它们。Sentry 通过自动抓取它们(通过标准)或允许您通过API上传它们来做到这一点。没有这个,假设你正在缩小代码,事情变得几乎无法使用。
  4. 最后一个主要问题是噪音。大多数浏览器扩展将直接注入您的脚本,因此您需要过滤掉噪音。我们通过两种方式解决这个问题:要忽略的模式黑名单(即“脚本错误”是最无用的),以及要接受的域白名单(即“example.com”)。我们发现两者的组合足以有效去除大多数随机噪声。

Some things you should be aware of on the server:

在服务器上你应该注意的一些事情:

  • Clients will sometimes persist open (i.e. a bot, or a bad user) and cause large amounts of useless data or simple old errors.
  • Your server should be able to handle a cascade of these events and fail gracefully. Sentry does this by rate limiting things and sampling data.
  • Exceptions are localized into the browser language, and without a centralized database you will be stuck translating them yourself (though its generally obvious what they mean).
  • 客户端有时会持续打开(即机器人或坏用户)并导致大量无用数据或简单的旧错误。
  • 您的服务器应该能够处理这些事件的级联并优雅地失败。Sentry 通过速率限制和采样数据来做到这一点。
  • 异常被本地化到浏览器语言中,如果没有集中的数据库,您将不得不自己翻译它们(尽管它们的含义通常很明显)。

回答by Martin Omander

If your website is using Google Analytics, you can do what I do:

如果您的网站使用的是 Google Analytics,您可以按照我的操作:

window.onerror = function(message, source, lineno, colno, error) {
  if (error) message = error.stack;
  ga('send', 'event', 'window.onerror', message, navigator.userAgent);
}

A few comments on the code above:

对上面代码的一些评论:

  • For modern browsers, the full stack trace is logged.
  • For older browsers that don't capture the stack trace, the error message is logged instead. (Mostly earlier iOS version in my experience).
  • The user's browser version is also logged, so you can see which OS/browser versions are throwing which errors. That simplifies bug prioritization and testing.
  • This code works if you use Google Analytics with "analytics.js", like this. If you are using "gtag.js" instead, like this, you need to tweak the last line of the function. See here for details.
  • 对于现代浏览器,会记录完整的堆栈跟踪。
  • 对于不捕获堆栈跟踪的旧浏览器,会记录错误消息。(根据我的经验,大多数是较早的 iOS 版本)。
  • 还会记录用户的浏览器版本,因此您可以查看哪些操作系统/浏览器版本引发了哪些错误。这简化了错误优先级排序和测试。
  • 如果您将 Google Analytics 与“analytics.js”一起使用,则此代码有效,如下所示。如果您使用的是“gtag.js”,就像这样,您需要调整函数的最后一行。有关详细信息,请参见此处

Once the code is in place, this is how you view your users' Javascript errors:

代码到位后,您可以通过以下方式查看用户的 Javascript 错误:

  1. In Google Analytics, click the Behaviorsection and then the Top Eventsreport.
  2. You will get a list of Event Categories. Click window.onerrorin the list.
  3. You will see a list of Javascript stack traces and error messages. Add a column to the report for your users' OS/browser versions by clicking the Secondary dimensionbutton and entering Event Labelin the textbox that appears.
  4. The report will look like the screenshot below.
  5. To translate the OS/browser strings to more human-readable descriptions, I copy-paste them into https://developers.whatismybrowser.com/useragents/parse/
  1. 在 Google Analytics 中,点击该Behavior部分,然后点击Top Events报告。
  2. 您将获得一个事件类别列表。window.onerror在列表中单击。
  3. 您将看到 Javascript 堆栈跟踪和错误消息的列表。通过单击Secondary dimension按钮并Event Label在出现的文本框中输入,为您的用户的操作系统/浏览器版本的报告添加一列。
  4. 该报告将类似于下面的屏幕截图。
  5. 要将操作系统/浏览器字符串转换为更易读的描述,我将它们复制粘贴到https://developers.whatismybrowser.com/useragents/parse/

enter image description here

在此处输入图片说明

回答by Tamil

If you want to do painless implementation just put up thisguys javascript code in your app. Else If you want to implement one, then try thisto get the stacktrace on windowerrorand you can use ajaxto report the errors. A nice wayto track errors reported by olark

如果您想轻松实现,只需在您的应用程序中放置这些人的 javascript 代码。其他如果你想实现一个,那么试试这个来获取堆栈跟踪windowerror,你可以ajax用来报告错误。一个很好的方式来跟踪错误报告olark

回答by Allan Ebdrup

http://exceptionhub.comShould to the trick. http://errorception.com/Does not provide as much information for debugging, but also seems nice.

http://exceptionhub.com应该要诀窍。 http://errorception.com/没有提供尽可能多的调试信息,但看起来也不错。

proxino don't seem to know what they are doing, they where incuding a complete jQuery in their logger code to log onerror events last time i checked. I wouldn't trust a service that has so little grasp of client side JavaScript to log my JavaScript errors.

proxino 似乎不知道他们在做什么,他们在他们的记录器代码中包含一个完整的 jQuery 来记录我上次检查时的错误事件。我不会相信一个对客户端 JavaScript 了解很少的服务来记录我的 JavaScript 错误。

回答by Alexey Petushkov

I recommend to use JsLog.meservice

我推荐使用JsLog.me服务

It can capture whole console output in addition to errors and stacktraces. We use it in our projects, logging whole console log helps our QA team to record issue-reproduction way. Also, it works well with large JSON objects like in Chrome console, and has a search.

除了错误和堆栈跟踪之外,它还可以捕获整个控制台输出。我们在我们的项目中使用它,记录整个控制台日志有助于我们的 QA 团队记录问题重现方式。此外,它适用于 Chrome 控制台等大型 JSON 对象,并具有搜索功能。

回答by Fizer Khan

Atatuscaptures JavaScript errors and also captures the user actions that preceded the error. This would help in better understanding of the error. Atatus helps you in monitoring your frontend, not just for errors, but also its performance(Real User Monitoring)

Atatus捕获 JavaScript 错误并捕获发生错误之前的用户操作。这将有助于更好地理解错误。Atatus 帮助您监控前端,不仅是错误,还有其性能(真实用户监控)

https://www.atatus.com/

https://www.atatus.com/

Disclaimer: I'm a web developer at Atatus.

免责声明:我是 Atatus 的一名网络开发人员。