How to work with alerts using the Splunk SDK for JavaScript

You can configure Splunk Enterprise to send alert messages to you and others when real-time or historical search results have met a set of circumstances that you define. These circumstances can include a wide range of threshold- and trend-based scenarios. For more information about alerts in Splunk Enterprise, see "About alerts."

The Splunk SDK for JavaScript gives you programmatic access to your Splunk Enterprise instance's fired alerts.

This topic contains the following sections:

The fired alert classes

The classes for working with alerts are:

Access these classes through an instance of the splunkjs.Service class. Retrieve the collection of all fired alert groups, and from there you can access individual alert groups in the collection and create new ones.

These new APIs are described in detail in "Alert APIs," and in the Splunk SDK for JavaScript API Reference section.

Code examples

This section provides examples of how to use the alert APIs, assuming you first connect to a Splunk Enterprise instance:

To list fired alerts

This example shows how to retrieve and list the fired alerts in all the fired alert groups.

function done(err) {
    //error handling logic here
}

// Get the collection of all fired alert groups for the current user
service.firedAlertGroups().fetch(function(err, firedAlertGroups) {

    // Get the list of all fired alert groups, including the all group (represented by "-")
    var firedAlertGroups = firedAlertGroups.list();
    console.log("Fired alert groups:");

    // For each fired alert group...
    for(var a in firedAlertGroups) {
        if (firedAlertGroups.hasOwnProperty(a)) {
            var firedAlertGroup = firedAlertGroups[a];
            firedAlertGroup.list(function(err, firedAlerts) {
                // How many times were this group's alerts fired?
                console.log(firedAlertGroup.name, "(Count:", firedAlertGroup.count(), ")");
                // Print the properties for each fired alert (default of 30 per alert group)
                for(var i = 0; i < firedAlerts.length; i++) {
                    var firedAlert = firedAlerts[i];
                    for(var key in firedAlert.properties()) {
                        if (firedAlert.properties().hasOwnProperty(key)) {
                           console.log("\t", key, ":", firedAlert.properties()[key]);
                        }
                    }
                    console.log();
                }
                console.log("======================================");
            });
        }
    }

    done();
});

For a complete code example that you can run in your browser, see the firedalerts.js example within the SDK's examples directory.

For a version of this example that uses the splunkjs.Async module to run asynchronously, see the firedalerts_async.js example within the SDK's examples directory.

To create an alert group

This example shows how to create an alert group. First, the example specifies the alert group's properties, and then it uses the service.savedSearches().create() function to create an alert group. Using alert-specific properties causes the report (saved search in Splunk Enterprise 5) to be created as an alert. To see all the alert-specific properties, see "Alert parameters." Alert-specific properties begin with "alert".

function done(err) {
    //error handling logic here
}

// Specify properties for the alert.
var alertOptions = {
    name: "My Awesome Alert",
    search: "index=_internal error sourcetype=splunkd* | head 10",
    "alert_type": "always",
    "alert.severity": "2",
    "alert.suppress": "0",
    "alert.track": "1",
    "dispatch.earliest_time": "-1h",
    "dispatch.latest_time": "now",
    "is_scheduled": "1",
    "cron_schedule": "* * * * *"
};

// Create a saved search/report as an alert.
service.savedSearches().create(alertOptions, function(err, alert) {
    // Error checking.
    if (err && err.status === 409) {
        console.error("ERROR: A saved search/report with the name '" + alertOptions.name + "' already exists");
        done();
        return;
    }
    else if (err) {
        console.error("There was an error creating the saved search/report:", err);
        done(err);
        return;
    }
	
    // Confirmation message.
    console.log("Created saved search/report as alert: " + alert.name);            
    done();
});

For a complete code example that you can run in your browser, see the firedalerts_create.js example within the SDK's examples directory.

To delete an alert group

This example shows how to delete an alert group. In particular, this example deletes the alert group that was created in the previous section. However, it does not delete the individual fired alerts within the alert group.

function done(err) {
    //error handling logic here
}

// The alert created earlier.
var name = "My Awesome Alert";

// Retrieve the alert group.
service.savedSearches().fetch(function(err, firedAlertGroups) {
    // Error checking.
    if (err) {
        console.log("There was an error in fetching the alerts");
        done(err);
        return;
    }

    // Get the alert group to delete using its name.
    var alertToDelete = firedAlertGroups.item(name);

    // Does the alert exist?
    if (!alertToDelete) {
        console.log("Can't delete '" + name + "' because it doesn't exist!");
        done();
    }
    else {
        // Delete the alert.
        alertToDelete.remove();
        console.log("Deleted alert: " + name + "");
        done();
    }
});

For a complete code example that you can run in your browser, see the firedalerts_delete.js example within the SDK's examples directory.

Alert APIs

Following are the alert-specific APIs in the Splunk SDK for JavaScript. This section includes the functions that each of the alert classes exposes.

The splunkjs.Service.FiredAlert class

The splunkjs.Service.FiredAlert class represents a fired alert, and extends the splunkjs.Service.Entity class. You can retrieve several of the fired alert's properties by calling the corresponding function. The splunkjs.Service.FiredAlert class exposes the functions listed in the following table.

Note: The values that these functions return can also be accessed through the properties() function, which is inherited from the splunkjs.Service.Entity class.

FunctionDescription
actions()Returns this alert's actions (such as e-mail notification, running a script, and so on).
alertType()Returns this alert's type.
expirationTime()Returns the rendered expiration time for this alert.
init(service, name, namespace)Constructor for splunkjs.Service.FiredAlert.
isDigestMode()Returns a Boolean value indicating whether the result is a set of events (a digest) or a single event (one per result).
path()Returns this alert's REST endpoint path.
savedSearchName()Returns this alert's report (saved search in Splunk Enterprise 5).
severity()Returns this alert's severity on a scale of 1 (highest) to 10.
sid()Returns this alert's search ID (SID).
triggerTime()Returns the time this alert was triggered.
triggerTimeRendered()Returns this alert's rendered trigger time.
triggeredAlertCount()Returns the count of triggered alerts.

The splunkjs.Service.FiredAlertGroup class

The splunkjs.Service.FiredAlertGroup class represents a group of alerts represented by a report (saved search in Splunk Enterprise 5), and extends the splunkjs.Service.Entity class. You can retrieve several of the fired alert group's properties by calling the corresponding function. The splunkjs.Service.FiredAlertGroup class exposes the functions listed in the following table.

Note: The values that these functions return can also be accessed through the properties() function, which is inherited from the splunkjs.Service.Entity class.

FunctionDescription
count()Returns the count of triggered alerts (the triggered_alert_count property).
init(service, name, namespace)Constructor for splunkjs.Service.FiredAlertGroup.
list()Returns a list of fired instances of this group's alerts (splunkjs.Service.Job instances).
path()Returns this group's REST endpoint path.

The splunkjs.Service.FiredAlertGroupCollection class

The splunkjs.Service.FiredAlertGroupCollection class represents a collection of fired alert groups, and extends the splunkjs.Service.Collection class. The splunkjs.Service.FiredAlertGroupCollection class exposes the functions listed in the following table.

FunctionDescription
init(service, namespace)Constructor for splunkjs.Service.FiredAlertGroupCollection.
instantiateEntity()Creates a local instance of a fired alert group, which is part of the fired alert group collection.
path()Returns this collection's REST endpoint path.
remove()Suppresses removing alerts via the fired alerts endpoint.

Alert-specific functions of the splunkjs.Service.SavedSearch class

The alert classes work with the following functions of the splunkjs.Service.SavedSearch class:

FunctionDescription
alertCount()Returns the count of triggered alerts for an alert group represented by the specified report (saved search in Splunk Enterprise 5).
firedAlertGroup()Returns the fired alert group (splunkjs.Service.FiredAlertGroup) associated with a given report (saved search in Splunk Enterprise 5).

Alert parameters

The properties that are available for alerts are the same as those for reports (saved searches in Splunk Enterprise 5). Alert-specific properties begin with "alert." The properties available for reports correspond to the parameters for the saved/searches endpoint in the REST API.

This table summarizes the properties you can set for an alert.

Parameter

Description

nameRequired. A string that contains the name of the report.
searchRequired. A string that contains the search query.
action.*A string with wildcard arguments to specify specific action arguments.
action.emailA Boolean that indicates the state of the email alert action. Read only.
action.email.auth_passwordA string that specifies the password to use when authenticating with the SMTP server. Normally this value is set while editing the email settings, but you can set a clear text password here that is encrypted when Splunk is restarted.
action.email.auth_usernameA string that specifies the username to use when authenticating with the SMTP server. If this is empty string, authentication is not attempted.
action.email.bccA string that specifies the BCC email address to use if "action.email" is enabled.
action.email.ccA string that specifies the CC email address to use if "action.email" is enabled.
action.email.commandA string that contains the search command (or pipeline) for running the action.
action.email.formatAn enum value that indicates the format of text and attachments in the email ("plain", "html", "raw", or "csv"). Use "plain" for plain text.
action.email.fromA string that specifies the email sender's address.
action.email.hostnameA string that specifies the hostname used in the web link (URL) that is sent in email alerts. Valid forms are "hostname" and "protocol://hostname:port".
action.email.inlineA Boolean that indicates whether the search results are contained in the body of the email.
action.email.mailserverA string that specifies the address of the MTA server to be used to send the emails.
action.email.maxresultsThe maximum number of search results to send when "action.email" is enabled.
action.email.maxtimeA number indicating the maximum amount of time an email action takes before the action is canceled. The valid format is number followed by a time unit ("s", "m", "h", or "d"), for example "5d".
action.email.pdfviewA string that specifies the name of the view to deliver if "action.email.sendpdf" is enabled.
action.email.preprocess_resultsA string that specifies how to pre-process results before emailing them.
action.email.reportCIDFontListMembers of an enumeration in a space-separated list specifying the set (and load order) of CID fonts for handling Simplified Chinese(gb), Traditional Chinese(cns), Japanese(jp), and Korean(kor) in Integrated PDF Rendering.
action.email.reportIncludeSplunkLogoA Boolean that indicates whether to include the Splunk logo with the report.
action.email.reportPaperOrientationAn enum value that indicates the paper orientation ("portrait" or "landscape").
action.email.reportPaperSizeAn enum value that indicates the paper size for PDFs ("letter", "legal", "ledger", "a2", "a3", "a4", or "a5").
action.email.reportServerEnabledA Boolean that indicates whether the PDF server is enabled.
action.email.reportServerURLA string that contains the URL of the PDF report server, if one is set up and available on the network.
action.email.sendpdfA Boolean that indicates whether to create and send the results as a PDF.
action.email.sendresultsA Boolean that indicates whether to attach search results to the email.
action.email.subjectA string that specifies the subject line of the email.
action.email.toA string that contains a comma- or semicolon-delimited list of recipient email addresses. Required if this search is scheduled and "action.email" is enabled.
action.email.track_alertA Boolean that indicates whether running this email action results in a trackable alert.
action.email.ttlThe number of seconds indicating the minimum time-to-live (ttl) of search artifacts if this email action is triggered. If the value is a number followed by "p", it is the number of scheduled search periods.
action.email.use_sslA Boolean that indicates whether to use secure socket layer (SSL) when communicating with the SMTP server.
action.email.use_tlsA Boolean that indicates whether to use transport layer security (TLS) when communicating with the SMTP server.
action.email.width_sort_columnsA Boolean that indicates whether columns should be sorted from least wide to most wide, left to right. This value is only used when "action.email.format"="plain", indicating plain text.
action.populate_lookupA Boolean that indicates the state of the populate-lookup alert action. Read only.
action.populate_lookup.commandA string that specifies the search command (or pipeline) to run the populate-lookup alert action.
action.populate_lookup.destA string that specifies the name of the lookup table or lookup path to populate.
action.populate_lookup.hostnameA string that specifies the host name used in the web link (URL) that is sent in populate-lookup alerts. Valid forms are "hostname" and "protocol://hostname:port".
action.populate_lookup.maxresultsThe maximum number of search results to send in populate-lookup alerts.
action.populate_lookup.maxtimeThe number indicating the maximum amount of time an alert action takes before the action is canceled. The valid format is number followed by a time unit ("s", "m", "h", or "d").
action.populate_lookup.track_alertA Boolean that indicates whether running this populate-lookup action results in a trackable alert.
action.populate_lookup.ttlThe number of seconds indicating the minimum time-to-live (ttl) of search artifacts if this populate-lookup action is triggered. If the value is a number followed by "p", it is the number of scheduled search periods.
action.rssA Boolean that indicates the state of the RSS alert action. Read only.
action.rss.commandA string that contains the search command (or pipeline) that runs the RSS alert action.
action.rss.hostnameA string that contains the host name used in the web link (URL) that is sent in RSS alerts. Valid forms are "hostname" and "protocol://hostname:port".
action.rss.maxresultsThe maximum number of search results to send in RSS alerts.
action.rss.maxtimeThe maximum amount of time an RSS alert action takes before the action is canceled. The valid format is number followed by a time unit ("s", "m", "h", or "d").
action.rss.track_alertA Boolean that indicates whether running this RSS action results in a trackable alert.
action.rss.ttlThe number of seconds indicating the minimum time-to-live (ttl) of search artifacts if this RSS action is triggered. If the value is a number followed by "p", it is the number of scheduled search periods.
action.scriptA Boolean that indicates the state of the script alert action. Read only.
action.script.commandA string that contains the search command (or pipeline) that runs the script action.
action.script.filenameA string that specifies the file name of the script to call, which is required if "action.script" is enabled.
action.script.hostnameA string that specifies the hostname used in the web link (URL) that is sent in script alerts. Valid forms are "hostname" and "protocol://hostname:port".
action.script.maxresultsThe maximum number of search results to send in script alerts.
action.script.maxtimeThe maximum amount of time a script action takes before the action is canceled. The valid format is number followed by a time unit ("s", "m", "h", or "d").
action.script.track_alertA Boolean that indicates whether running this script action results in a trackable alert.
action.script.ttlThe number of seconds indicating the minimum time-to-live (ttl) of search artifacts if this script action is triggered. If the value is a number followed by "p", it is the number of scheduled search periods.
action.summary_indexA Boolean that indicates the state of the summary index alert action. Read only.
action.summary_index._nameA string that specifies the name of the summary index where the results of the scheduled search are saved.
action.summary_index.commandA string that contains the search command (or pipeline) that runs the summary-index action.
action.summary_index.hostnameA string that specifies the hostname used in the web link (URL) that is sent in summary-index alerts. Valid forms are "hostname" and "protocol://hostname:port".
action.summary_index.inlineA Boolean that indicates whether to run the summary indexing action as part of the scheduled search.
action.summary_index.maxresultsThe maximum number of search results to send in summary-index alerts.
action.summary_index.maxtimeA number indicating the maximum amount of time a summary-index action takes before the action is canceled. The valid format is number followed by a time unit ("s", "m", "h", or "d"), for example "5d".
action.summary_index.track_alertA Boolean that indicates whether running this summary-index action results in a trackable alert.
action.summary_index.ttlThe number of seconds indicating the minimum time-to-live (ttl) of search artifacts if this summary-index action is triggered. If the value is a number followed by "p", it is the number of scheduled search periods.
actionsA string that contains a comma-delimited list of actions to enable, for example "rss,email".
alert.digest_modeA Boolean that indicates whether Splunk applies the alert actions to the entire result set or digest ("true"), or to each individual search result ("false").
alert.expiresThe amount of time to show the alert in the dashboard. The valid format is number followed by a time unit ("s", "m", "h", or "d").
alert.severityA number that indicates the alert severity level (1=DEBUG, 2=INFO, 3=WARN, 4=ERROR, 5=SEVERE, 6=FATAL).
alert.suppressA Boolean that indicates whether alert suppression is enabled for this scheduled search.
alert.suppress.fieldsA string that contains a comma-delimited list of fields to use for alert suppression.
alert.suppress.periodA value that indicates the alert suppression period, which is only valid when "Alert.Suppress" is enabled. The valid format is number followed by a time unit ("s", "m", "h", or "d").
alert.trackAn enum value that indicates how to track the actions triggered by this report. Valid values are: "true" (enabled), "false" (disabled), and "auto" (tracking is based on the setting of each action).
alert_comparatorA string that contains the alert comparator. Valid values are: "greater than", "less than", "equal to", "rises by", "drops by", "rises by perc", and "drops by perc".
alert_conditionA string that contains a conditional search that is evaluated against the results of the report.
alert_thresholdA value to compare to before triggering the alert action. Valid values are: integer or integer%. If this value is expressed as a percentage, it indicates the value to use when "alert_comparator" is set to "rises by perc" or "drops by perc".
alert_typeA string that indicates what to base the alert on. Valid values are: "always", "custom", "number of events", "number of hosts", and "number of sources". This value is overridden by "alert_condition" if specified.
args.*A string containing wildcard arguments for any report template argument, such as "args.username"="foobar" when the search is search $username$.
auto_summarizeA Boolean that indicates whether the scheduler ensures that the data for this search is automatically summarized.
auto_summarize.commandA string that contains a search template that constructs the auto summarization for this search.
auto_summarize.cron_scheduleA string that contains the cron schedule for probing and generating the summaries for this report.
auto_summarize.dispatch.earliest_timeA string that specifies the earliest time for summarizing this report. The time can be relative or absolute; if absolute, use the "dispatch.time_format" parameter to format the value.
auto_summarize.dispatch.latest_timeA string that contains the latest time for summarizing this report. The time can be relative or absolute; if absolute, use the "dispatch.time_format" parameter to format the value.
auto_summarize.dispatch.ttlThe number of seconds indicating the time to live (in seconds) for the artifacts of the summarization of the scheduled search. If the value is a number followed by "p", it is the number of scheduled search periods.
auto_summarize.max_disabled_bucketsA number that specifies the maximum number of buckets with the suspended summarization before the summarization search is completely stopped, and the summarization of the search is suspended for the "auto_summarize.suspend_period" parameter.
auto_summarize.max_summary_ratioA number that specifies the maximum ratio of summary size to bucket size, which specifies when to stop summarization and deem it unhelpful for a bucket. The test is only performed if the summary size is larger than the value of "auto_summarize.max_summary_size".
auto_summarize.max_summary_sizeA number that specifies the minimum summary size, in bytes, before testing whether the summarization is helpful.
auto_summarize.max_timeA number that specifies the maximum time (in seconds) that the summary search is allowed to run. Note that this is an approximate time because the summary search stops at clean bucket boundaries.
auto_summarize.suspend_periodA string that contains the time indicating when to suspend summarization of this search if the summarization is deemed unhelpful.
auto_summarize.timespanA string that contains a comma-delimited list of time ranges that each summarized chunk should span. This comprises the list of available granularity levels for which summaries would be available.
cron_scheduleA string that contains the cron-style schedule for running this report.
descriptionA string that contains a description of this report.
disabledA Boolean that indicates whether the report is enabled.
dispatch.*A string that specifies wildcard arguments for any dispatch-related argument.
dispatch.bucketsThe maximum number of timeline buckets.
dispatch.earliest_timeA time string that specifies the earliest time for this search. Can be a relative or absolute time. If this value is an absolute time, use "dispatch.time_format" to format the value.
dispatch.latest_timeA time string that specifies the latest time for this report. Can be a relative or absolute time. If this value is an absolute time, use "dispatch.time_format" to format the value.
dispatch.lookupsA Boolean that indicates whether lookups for this search are enabled.
dispatch.max_countThe maximum number of results before finalizing the search.
dispatch.max_timeThe maximum amount of time (in seconds) before finalizing the search.
dispatch.reduce_freqThe number of seconds indicating how frequently Splunk runs the MapReduce reduce phase on accumulated map values.
dispatch.rt_backfillA Boolean that indicates whether to back fill the real-time window for this search. This value is only used for a real-time search.
dispatch.spawn_processA Boolean that indicates whether Splunk spawns a new search process when running this report.
dispatch.time_formatA string that defines the time format that Splunk uses to specify the earliest and latest time.
dispatch.ttlThe number indicating the time to live (ttl) for artifacts of the scheduled search (the time before the search job expires and artifacts are still available), if no alerts are triggered. If the value is a number followed by "p", it is the number of scheduled search periods.
displayviewA string that contains the default UI view name (not label) in which to load the results.
is_scheduledA Boolean that indicates whether this report runs on a schedule.
is_visibleA Boolean that indicates whether this report is visible in the report list.
max_concurrentThe maximum number of concurrent instances of this search the scheduler is allowed to run.
next_scheduled_timeA string that indicates the next scheduled time for this report. Read only.
qualifiedSearchA string that is computed during run time. Read only.
realtime_scheduleA Boolean that specifies how the scheduler computes the next time a scheduled search is run:
  • When "true": The schedule is based on the current time. The scheduler might skip some scheduled periods to make sure that searches over the most recent time range are run.
  • When "false": The schedule is based on the last search run time (referred to as "continuous scheduling") and the scheduler never skips scheduled periods. However, the scheduler might fall behind depending on its load. Use continuous scheduling whenever you enable the summary index option ("action.summary_index").

The scheduler tries to run searches that have real-time schedules enabled before running searches that have continuous scheduling enabled.

request.ui_dispatch_appA string that contains the name of the app in which Splunk Web dispatches this search.
request.ui_dispatch_viewA string that contains the name of the view in which Splunk Web dispatches this search.
restart_on_searchpeer_addA Boolean that indicates whether a real-time search managed by the scheduler is restarted when a search peer becomes available for this report. The peer can be one that is newly added or one that has become available after being down.
run_on_startupA Boolean that indicates whether this search is run when Splunk starts. If the search is not run on startup, it runs at the next scheduled time. It is recommended that you set this value to "true" for scheduled searches that populate lookup tables.
vsidA string that contains the view state ID that is associated with the view specified in the "displayview" attribute.