Created
May 1, 2017 22:53
-
-
Save DinoChiesa/acff1afb2ea5e3577f6039923906bbdb to your computer and use it in GitHub Desktop.
JS Callout code to log to Splunk using a HEC token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// log-To-Splunk.js | |
// ------------------------------------------------------------------ | |
// | |
// Fill a message template, then POST to splunk without waiting for a response. | |
// | |
// created: Wed Feb 15 16:28:55 2017 | |
// last saved: <2017-March-08 18:28:03> | |
var variableNameRe = "[^ \t\n\"',/\\\\]+?"; // non-greedy capture | |
var varPrefixRe = '{'; | |
var varSuffixRe = '}'; | |
var variableRegex = new RegExp( varPrefixRe + '(' + variableNameRe + ')' + varSuffixRe, 'g'); | |
function fillTemplate(template) { | |
// substitute all names surrounded by {curly_braces} in the template | |
// with the value of the corresponding context variables | |
var match; | |
while ((match = variableRegex.exec(template)) !== null) { | |
var variableName = match[1]; | |
var value = context.getVariable(variableName); | |
if (value && value !== '') { | |
template = template.replace('{' + variableName + '}', value); | |
} | |
else { | |
template = template.replace('{' + variableName + '}', 'n/a'); | |
} | |
} | |
return template + ''; // coerce to JS String | |
} | |
// fire and forget | |
var payload = fillTemplate(properties.payload); | |
var headers = { | |
'Content-Type' : 'application/json', | |
'Authorization' : fillTemplate(properties.authz_header) | |
}; | |
var url = fillTemplate(properties.endpoint); | |
var req = new Request(url, 'POST', headers, payload); | |
var exchange = httpClient.send(req); | |
// Conditionally wait for a response from Splunk. This is gated on a | |
// flag that is stored in the KVM. Should set the flag true only for | |
// diagnostic purposes. Also, when waiting, the timeLimit on the JS | |
// callout should be 1000ms or more, to accommodate the HEC delay. | |
var wantWait = context.getVariable('splunk_await_response'); | |
if (wantWait && wantWait.toLowerCase() == "true") { | |
exchange.waitForComplete(); | |
if (exchange.isError()) { | |
throw "error: " + exchange.getError() + ", while retrieving"; | |
} | |
var responseBody = exchange.getResponse(); | |
context.setVariable('splunk_response', responseBody); | |
} | |
else { | |
context.setVariable('splunk_response', "-did not wait-"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment