Splunk Developer Day: Watch all Sessions!Access the Playlist here

How to log to HTTP Event Collector using Splunk logging for JavaScript

The main purpose of Splunk logging for JavaScript is to log event data to HTTP Event Collector (HEC) running on Splunk Enterprise or on Splunk Cloud Platform. This topic covers a basic example that is included in the Splunk logging for JavaScript repo. The example shows how to use the library's Logger object to package and send events to HEC. The basic.js example is included in the examples directory of the Splunk logging for JavaScript package, and it has also been pasted below.

Info

The examples are not installed when using the npm installation method. For a copy of the examples, go to Downloads and download the Splunk logging for JavaScript package.

Example walkthrough

This example includes logic to send data to HTTP Event Collector on Splunk Enterprise or Splunk Cloud Platform using a Logger object.

First, we declare a SplunkLogger variable based on the library's Logger object.

Then, we declare a config variable to store the configuration information for the Splunk Enterprise instance or Splunk Cloud Platform server. Only the token property is required, but in this example, we've also set the url property:

  • token: The HTTP Event Collector token to use. You created this in Requirements and Installation.
  • url: The protocol, hostname, and HEC port (8088 by default) of either your Splunk Enterprise instance or your Splunk Cloud Platform server.

You can also set the following common properties. For all possible properties, see splunklogger.js(Opens new window)

  • path: The REST endpoint for HTTP Event Collector.
  • protocol: The protocol to use. This value will be either http or https.
  • level: The logging level to use. This value can be one of the following: trace, debug, info, warn or error.

Next, we add an error handler (Logger.error).

Then, we define the event payload in the payload variable. At minimum, we need some sort of message to send. The other keys, metadata and severity, are optional. In this case, we've added two key-value pairs, but the contents of the message key can be anything at all. The contents of metadata will be assigned to this event when Splunk Enterprise or Splunk Cloud Platform indexes the event. If any of these values (source, sourcetype, and so on) differ from the default values on the server, the values specified here will override the default values. Of course, your JavaScript app will determine what goes into the actual payload.

Finally, we send the payload (Logger.send) and log the response from Splunk Enterprise or Splunk Cloud Platform.

basic.js

/*
* Copyright 2015 Splunk, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"): you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0