Pricing Login
Pricing
Support
Demo
Interactive demos

Click through interactive platform demos now.

Live demo, real expert

Schedule a platform demo with a Sumo Logic expert.

Start free trial
Back to blog results

April 26, 2017 By Bill Lazar

Add Logging to Your Apps with the New Sumo Logic Javascript Logging SDK

[Updated Nov. 7, 2018: With the release of v2.0 of the SDK, much of the original content has changed or is different. The biggest change is deprecation of the original (browser) module as the CommonJS module handles both browser and server use cases. This blog post has been changed to reflect usage as of v2.0.]

Many apps today are written in Javascript for both the front end UI and server and this new SDK, available on Github, is intended to make integrating Sumo Logic with your Javascript application easier and more dependable.

The SDK provides a convenient wrapper for sending log messages and metrics to HTTP sources in your account and includes a CommonJS module suitable for use in a browser as well as Node.js/server apps. Log messages and metrics are sent as structured JSON objects and can be batched for sending at intervals to minimize network traffic or individually.

A demo app is included in the node-example directory with an HTML page that lets you send messages to your own endpoint.

The Node.js Example Page

Prerequisites

Before we dive in, please note that you must have an HTTP source in your Sumo Logic account to use this SDK. To create one, log into Sumo Logic, go to the Collectors page and add a new HTTP source to a new or existing Hosted Collector. You’ll need the endpoint URL to configure the logger object.

If you don’t have a Sumo Logic account yet, you can quickly Sign Up Freethere’s no cost, just enter your email.

Please review the “Security Note” section at the end of this article before planning your implementation.

Configuration options

The log object exposes a number of properties you may configure, and while most are useful only the HTTP source endpoint is required.

  • endpoint: HTTP source URL (required)
  • interval: an integer specifying the milliseconds between sending messages
  • sendErrors: true, defaults to FALSE, only pass this to NOT send all unhandled errors to Sumo Logic (Vanilla JS version only)
  • sessionKey: a GUID identifier
  • sourceName: metadata value for searches
  • sourceCategory: metadata value for searches
  • hostName: metadata value for searches
  • Graphite: sends Graphite formatted messages
  • returnPromise: causes the log function to return a promise (only used when messages are sent individually)
  • onSuccess: function() { … a callback to handle successful sends …. } (not used when returnPromise is true)
  • onError: function() { … a callback to handle handle errors …. } (not used when returnPromise is true)

Using the SDK

Other than configuring the logger, usage is straightforward: Simply call the logger’s log() function with the message or messages to be logged. The function accepts a string or a JSON object, or an array of strings or JSON objects. Messages are queued until the sync interval is reached and then send to the endpoint. You may supply success and error callback functions to be called in either circumstance and the returnPromise flag is not enabled.

The log function accepts a second parameter, an object, so you can configure a few values on a per-message basis:

  • sessionKey: Override the default sessionKey value supplied when the logger object was instantiated.
  • timestamp: Override the default timestamp for the message (otherwise new Date() is sent).
  • url: Page URL from which the log message was sent (Node.js version only)

There are two additional utility functions:

  • emptyLogQueue: Clears any unsent messages from the queue
  • flushLogs: Immediately sends any unsent messages, which should be called from your shutdown or unload handlers to ensure all messages are sent to Sumo Logic.

Calling the logger’s log function:

// <span>Node.js (u</span><span>sing Express middleware)</span>
var sumoLogger = require('../src/sumoLogger.js');
var opts = {
 endpoint: '[Your HTTP source endpoint goes here]',
 clientUrl: 'https://myapp.example.com',
 interval: 10000,
 // generate a GUID or inject standard session key
 sessionKey: 'Abc32df34rfg54gui8j098dv13sq5re', 
 sourceName: 'My Custom App',
 sourceCategory: 'My Source Category',
 hostName: 'My Host Name',
 onSuccess: function () {
 console.log('Sumo Logic success callback executed');
 },
 onError: function () {
 console.log('Sumo Logic error callback executed');
 }
};

// ...
var logSumo = new sumoLogger(opts);

// ...
app.post('/sendLog', function (req, res) {
 var msg = req.body.msg;
 var opts = {};
 if (req.body.url) {
 opts.url = req.body.url;
 }
 logSumo.log(msg, opts);
 res.send(true);
});
// In-browser JS
<script src=”/path/to/sumologic.logger.js”></script>
// ...
<script>
var messageData = [
 {'testingKey': 'Testing from example page'},
 {'testingKey': 'Second test log line'}
];
SLLogger.log(messageData);
</script>

Please review the two demos’ source files for more detail.

Feedback and Issues

I’d love to hear from people who use the SDK, especially if you have ideas to make it better. Issues should be filed on the Github repo’s issues page.

Security Note

Sumo Logic is always concerned with security but some instances call for balancing risk with value of functionality. Using the this library directly from the browser is one such situation.

Hitting an HTTP source endpoint from code running in a web browser exposes the endpoint URL to anyone inspecting the code or running your app with the browser console open to the network tab. There is no means to obfuscate or hide this. The risk is some malicious individual will send additional traffic to the endpoint, potentially using up your ingest or polluting your searches.

If this is a concern for you, we recommend using the the SDK from your server app so your endpoint URL is never exposed.

One method for minimizing the damage from some malicious users, should you choose to use this or other similar code in the browser, is adding an arbitrary string based on a regex to your log message and adding a processing rule to the HTTP source configuration that blocks incoming messages which lack a match for the regex.

Complete visibility for DevSecOps

Reduce downtime and move from reactive to proactive monitoring.

Categories

Sumo Logic cloud-native SaaS analytics

Build, run, and secure modern applications and cloud infrastructures.

Start free trial

Bill Lazar

More posts by Bill Lazar.