7

Possible Duplicate:
Logging Clientside JavaScript Errors on Server

How can I log client side javascript errors to the server? I'm using jQuery and MVC.

Community
  • 1
  • 1
Karl Glennon
  • 3,149
  • 4
  • 29
  • 31
  • I'm using the Elmah logging framework at the moment. Is there any way to link a solution into this? – Karl Glennon May 13 '10 at 11:44
  • 1
    I found this nice hosted solution to the problem recently: http://errorception.com/ – Karl Glennon Apr 06 '12 at 14:58
  • JSNLog (jsnlog.com) lets you log strings and objects on the client in your JavaScript, and store them on the server using Elmah. You just specify Elmah when you install JSNLog. – user1147862 Nov 08 '13 at 14:12
  • If you are using Google Analytics on your website, logging client-side errors is easy and free: https://stackoverflow.com/a/52248397/455313 – Martin Omander Sep 09 '18 at 20:44

2 Answers2

16

Since they're client-side errors, you'll have to send them to the server using XMLHttpRequest. You could use try...catch statements or window.onerror:

window.onerror = function (msg, url, line)
{
    var message = "Error in "+url+" on line "+line+": "+msg;
    $.post("logerror.aspx", { "msg" : message }); 
}

Be aware that line and url can be very inaccurate in IE versions prior to 8.

Andy E
  • 338,112
  • 86
  • 474
  • 445
6

You could use my log4javascript, which has an appender that uses XMLHttpRequest to log to the server:

var log = log4javascript.getLogger("serverLog");
var ajaxAppender = new log4javascript.AjaxAppender("clientlogger.jsp");
log.addAppender(ajaxAppender);

try {
    nonExistentFunction();
} catch(ex) {
    log.error("Something's gone wrong!", ex);
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Thanks for this suggestion. Do you know if it is possible to link this to log4net ? – Karl Glennon May 13 '10 at 11:44
  • It's easy enough to do it manually. The default way the `AjaxAppender` sends logging data is as an HTTP post with parameters representing aspects of the logging event, such as the message, timestamp, severity etc. On the server, you'd have a page or HTTP handler to receive the post, and make a log4net call based on the post parameters. – Tim Down May 14 '10 at 09:10
  • JSNLog (jsnlog.com) does all this for you out of the box. It consists of a JavaScript logging library and a server side dll that receives log messages from the JavaScript library and passes them on to your server side logger library, such as Log4Net, NLog or Elmah. It lets you configure your JavaScript loggers in your web.config. And it has all sorts of features such as suppressing duplicate messages, message batching and filtering by browser type. – user1147862 Nov 02 '13 at 01:19
  • @user1147862: Sounds good. I have deliberately not focussed on the server part in log4javascript, so this seems like a useful library for .NET developers. I'd suggest adding an answer if this question wasn't closed. – Tim Down Nov 02 '13 at 12:22