Best way to capture JavaScript errors in production?

rsturim picture rsturim · Sep 13, 2010 · Viewed 10.7k times · Source

I've got a serious JavaScript problem that is hard to reproduce in any of our dev/test/prod environments. Nonetheless, it is being reported consistently by our customers. Sometimes we think it's browser specific -- sometimes we think it's action specific -- sometimes we think it's cookie related. It's a tough one and we're getting pulled in too many different directions and they are all coming up short.

We believe the problem occurs in one of our main JavaScript files -- but that file is enormous. We've pin-pointed other problems in the past in this file -- and guarded against future problems using try/catch blocks successfully -- but, at this time we're very unsure where these newer problems are occurring.

We've searched through our server logs and the information we are finding there is not useful.

I am wondering if utilizing a JavaScript logging framework would help our problems. Will implementing something like "log4javascript" capture/log the activity of our users, not just us? Any advice? Anyone else been in this situation? What strategies did you employ to better understand your errors?

Answer

Tim Down picture Tim Down · Sep 13, 2010

log4javascript's AjaxAppender can be used to send log messages to the server.

var log = log4javascript.getLogger("serverlog");
var ajaxAppender = new log4javascript.AjaxAppender("http://example.com/clientlogger");
log.addAppender(ajaxAppender);

You could put informational logging calls in your code and add a window.onerror handler to catch errors not caught by try/catch blocks in your code:

window.onerror = function(errorMsg, url, lineNumber) {
    log.fatal("Uncaught error " + errorMsg + " in " + url + ", line " + lineNumber);
};

You will also need to create something on the server to process the logging requests from the browser.

Full disclosure: I am the author of log4javascript.