npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

browser-telemetry

v1.0.1

Published

Browser side logger for Web Apps

Downloads

11

Readme

Browser-Telemetry

browser-telemetry module collects client(browser) side errors, logs, metrics(timing & navigation), uncaught exceptions etc and sends back to server for logging & alerting.

Features

  • Intercept console.log/error/info/warn on browser
  • Intercept Uncaught Exceptions on browser
  • Batch update
  • Timing & Navigation metrics
  • Sampling (Browser side & Server Side)
  • Custom Data Provider plugins

Future Enhancements

  • Rate Limiting
  • Token based API access
  • CORS

Usage

Environment

  • Minimal Node Version: v8.0.0

Client Side Usage

Add logger.min.js in header section to load it first, as it hooks console, there by intercepting all JS errors. (see below example)

    <script src="static/logger.min.js">
    </script>

Minified JS logger.min.js

Example:

<html>
    <head>
        <script src="static/logger.min.js">
        </script>

        <script>
            function logData() {
                $logger.init({ 'url': '/api/log', 'flushInterval': 1000, 'samplingRate': 50, 'sendMetrics': true});

                $logger.registerPlugin('custom', function(payload) {
                    payload.custom = {
                        'Pagename': 'HomePage'                        
                    };
                });
                $logger.log('Hello, Logging Data!!');

                //Console
                console.log('Hello, from console.log');
                console.error('Hello, from console.error');
                console.info('Hello, from console.info');

                //Client Side Uncaught Exception
                throw new Error('Uncaught Error');
            }
        </script>
    </head>
    <body onload="logData()">
            <h1>Hello World!!</h1>
    </body>

</html>

Server Side Usage

    
    let app = express();
    const path = path.resolve('browser-telemetry');
    app.use('/static', express.static(path.join(path, '../browser')));
    app.use(bodyParser.json({ type: 'application/*+json' }));
    app.use(bodyParser.json({ type: 'text/plain' }));

    //require Logger
    let loggerMiddleware = require('./');
    
    //Add Logger Middleware
    app.use(loggerMiddleware({
        path: '/api/log',
        log: function(req, payload) {
            console.log('Metrics:', payload.metrics);   
            
            //Consoles from Client Side            
            payload.logs.forEach((event) => {
                console.log(`${event.level}: ${JSON.stringify(event.msg)}`);
            });   
            console.log('Custom Plugin Data:', payload.custom);   
        }
    }));

Payload Data

  • logs/errors: ALL console logs/errors are intercepted and sent in logs field.
  • Uncaught Exceptions: ALL uncaught exceptions are intercepted and sent in logs field as ERROR.
  • Metrics: Browser load times are captured using timing & navigation API(Only in compatible browsers).
    • rc: Redirect Count, number of times page is redirected before hitting current page.
    • lt: Load Time, load time of the page.
    • ct: Connect Time, time took to connect to server.
    • rt: Render Time, time took to render the page.
    • navType: Tells you how the page is accessed. 0=Navigate, 1=Reload, 2=History
{
  "metrics": {
    "navType": 0,
    "rc": 0,
    "lt": 255,
    "ct": 72,
    "rt": 147
  },
  "logs": [
    {
      "level": "LOG",
      "msg": "Hello, Logging Data!!"
    },
    {
      "level": "LOG",
      "msg": "Hello from console.log"
    },
    {
      "level": "ERROR",
      "msg": "Hello from console.error"
    },
    {
      "level": "INFO",
      "msg": "Hello from console.info"
    },
    {
      "level": "ERROR",
      "msg": "Uncaught Error: Uncaught http://localhost:8080/ 20 23 Error: Uncaught\n    at logData (http://localhost:8080/:20:23)\n    at onload (http://localhost:8080/:24:30)"
    }
  ],
  "custom": {
    "pageName": "HomePage"
  }
}

API

Client Side API

  • $logger

    On load of Javascript file, $logger object gets hooked up to window object for global access.

  • $logger.init(object)

    For initializing logger, call this API. Input:

    {
        "url": "api/log", //Relative path
        "flushInterval": 1000, //1sec,
        "samplingRate": 10, //10%, Client Side Sampling
        "isInSampling": true, //Flag from Server Side Sampling
        "sendMetrics": true, //Flag to send metrics or not
        "logLevels": ["info", "log", "debug", "error", "warn"] //List of enabled console methods
    }
  • $logger.registerPlugin(pluginName, callback)

    • callback(payload) Some times you need to send your own custom data. You can attach custom data or transform data by registering your own plugin. Payload object will be passed, which can be mutated in callback.

    On every flush, ALL registered plugins gets called for data transformation.

        $logger.registerPlugin('custom', function(payload) {
            payload.Pagename = 'HomePage';
        });

Server Side API

  • Middleware

    require('browser-telemetry')(options)

    • options:

      • path: Path on which logger should be mounted. This is the end where events from browser are posted.
      • log: A callback function which will be invoked on every event from client side.
        • request: Holds HTTP request object
        • payload: A payload which holds events from browser.
          const loggerMiddleware = require('browser-telemetry');
          let app = reqiure('express');
          ...
          app.use(loggerMiddleware({
              path: 'path/to/mount',
              log: function(req, payload) {
                  console.log(payload);
              }
          }));
  • Log Hook

    As an app developer, you can intercept browser events by hooking to log callbacks. Simply pass your custom function while registering middleware as shown below.

    Browser events are populated in payload param.

        app.use(loggerMiddleware({
            path: 'path/to/mount',
            log: function(req, payload) {
                console.log(payload);
            }
        }));

File Size

Main motivation for creating this module is to reduce file size. Currently, minified client side JS file size is ~2KB.

Example

See the working example in example folder.

Running Example Server

    node example/server.js

    //Open Browser pointing to http://localhost:8080
    //ALl Logs/Metrics will be dumped on Server side console.

Ackowledgement

This module is created as an inspiration from beaver-logger. Main motivation is to reduce client side JS file size and provide minimal functionality for intercepting logs/metrics/uncaught exceptions on browser side.

Privacy Notice

On running this module/Javascript file on browser, it collects page load metrics, console logs, error logs, unhandled exceptions etc and sends data to backend server for processing.

License

Copyright 2018 eBay Inc.

Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT.