ANTON072
6/30/2015 - 10:37 AM

Client-side error logging with Google Analytics

Client-side error logging with Google Analytics

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">

    <title>Logging Test for Google Analytics</title>

    <style>
      button {
        position: relative;
        width: 200px;
      }
      .normal {
        background-color: #fff;
        color: #000;
      }
      .error {
        background-color: #ffefef;
        color: #f00;
      }
      #message {
        font-family: monospace;
      }
    </style>

    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-44327970-2', 'auto');
      ga('send', 'pageview');
    </script>

    <script defer>
      // `ga` should not be in this local scope somehow...
      (function (w, d, n) {

        // HTML logging
        var htmlOut = function (msg, isError) {
          var messageEl = d.getElementById('message');
          messageEl.className = isError ? 'error' : 'normal';
          messageEl.textContent = msg;
        };

        /**
         * Error tracking as Exception Tracking
         * @see https://developers.google.com/analytics/devguides/collection/analyticsjs/exceptions
         */
        var errorTracker = function (err, isFatal) {
          // Error message format from GNU Coding Standards
          var msg = err.filename + ':' + err.lineno + ':' + err.colno + ': ' + '"' + err.message + '"';

          // Send the error to Google Analytics
          ga('send', 'exception', {
            'exDescription': msg,
            'exFatal': (false !== isFatal) ? true : false
          });

          htmlOut(msg, true);
          //console.error(err.message);
        };

        /**
         * Log tracking as Event Tracking
         * @see https://developers.google.com/analytics/devguides/collection/analyticsjs/events
         */
        var logTracker = function (stack, isError) {
          // Send the event to Google Analytics
          ga('send', {
            'hitType': 'event',
            'eventCategory': isError ? 'warning' : 'log',
            'eventAction': 'log',
            'eventValue': stack
          });

          htmlOut(stack, isError ? true : false);
          console[isError ? 'warn' : 'log'](stack);
        };

        // Test to throw an exception
        var exception = function (ev) {
          var message = 'A test exception threw.';
          throw new Error(message);
        };

        // Test to handle an error
        var error = function (ev) {
          try {
            exception();
          } catch (stack) {
            logTracker(stack, true);
          }
        };

        // Test to record a log
        var log = function (ev) {
          var msg = 'A test logging.';
          logTracker(msg, false);
        };

        // Main process
        var main = function (ev) {
          // Listen to test triggers
          d.getElementById('exception').addEventListener('click', exception, false);
          d.getElementById('error').addEventListener('click', error, false);
          d.getElementById('log').addEventListener('click', log, false);

          // Remove DOM ready listener
          ev.target.removeEventListener(ev.type, main);
        };

        // Listen to DOM ready
        d.addEventListener('DOMContentLoaded', main, false);

        // Listen to errors
        w.addEventListener('error', errorTracker, false);

      })(window, document, navigator);
    </script>

  </head>
  <body>
    <p>
      <button id="exception"> Throw an exception</button>
      <button id="error">Handle an Error</button>
      <button id="log">Record a log</button>
    </p>
    <p id="message"></p>
  </body>
</html>