Creating a Splunk Javascript View

Once of the best things about Splunk is the ability to customize it. Splunk allows you to make your own Javascript views without imposing many limitations on you. This means you make apps that includes things such as:

  • Custom editors or management interfaces (e.g. lookup editing, slide-show creation)
  • Custom visualizations (though modular visualizations are likely what you will want to use from now on)
  • etc.

That said, getting started on creating a Splunk Javascript view can appear a little daunting at first. It really isn’t that hard though. Keep reading and I’ll explain how to do it.

Parts of a Splunk Javascript View

Before we get started, lets outline the basic parts of a custom Javascript view:

Component Path Example Description
Javascript view file appserver/static/js/views/HelloSplunkJSView.js This is the main view Javascript file
HTML template file appserver/static/js/templates/HelloSplunkJSView.html This is where you can put HTML you want to be rendered
Stylesheet file appserver/static/css/HelloSplunkJSView.css Here is where you put your custom CSS
Third party libraries appserver/static/contrib/text.js Include any third-party libraries under a contrib directory
Splunk View default/data/ui/views/hellosplunkjs.xml This is the view where the custom view will appear
View Javascript file appserver/static/hellosplunkjs.js This Javascript will put your custom view on the dashboard

Lets get started

We are going to make a very simple app that will allow you to run a search and get the most recent event. The completed app is available on Github for your reference.

Step 1: make a basic Splunk app

We are going to put out content into a basic Splunk app. To do this, we will make a few files inside of a Splunk install.

Step 1.1: make app directory

First, make a directory in your Splunk install under the /etc/apps directory for the app you are going to create. I’m going to name the app “hello-splunkjs”. Thus, I will make the following directory: /etc/apps/hello-splunkjs

Step 1.2: make app.conf

Now, lets make the app.conf file. This goes here in your Splunk install: /etc/apps/hello-splunkjs/default/app.conf

The contents will just be this:

[launcher]
version = 0.5
description = Example of writing basic SplunkJS views

[ui]
is_visible = true
label = Hello SplunkJS 

You should see the app in Splunk If you restart it.

Step 2: make the basic view

Now let’s get started making the view.

Step 2.1: deploy the template

Now, let’s make the basic Javascript view file. To make things a little easier, you can start with the template available on Github. The Javascript views ought to be placed in your app in the /appserver/static/js/views/ directory. In our case, the view will be in /etc/apps/hello-splunkjs/appserver/static/js/views/HelloSplunkJSView.js.

All of the places in the template with a CHANGEME will be replaced in the next few steps.

Step 2.2: update the app references

We need to update the references in the require.js statement to point to your app. This is done by changing /app/CHANGEME to /app/hello-splunkjs (since our app directory is hello-splunkjs). This results in the following at the top of/etc/apps/hello-splunkjs/appserver/static/js/views/HelloSplunkJSView.js:

define([
    "underscore",
    "backbone",
    "splunkjs/mvc",
    "jquery",
    "splunkjs/mvc/simplesplunkview",
    'text!../app/hello-splunkjs/js/templates/CHANGEMEView.html', // Changed to 
    "css!../app/hello-splunkjs/css/CHANGEMEView.css" // CHANGE_THIS: Modify the path to use a template
], function(

See the diff in Github.

Step 2.3: add the template and stylesheet files

We now need to add the files that will contain the stylesheet and the HTML. For the stylesheet, make an empty file in /etc/apps/hello-splunkjs/appserver/static/css/HelloSplunkJSView.css. We will leave it empty for now.

For the HTML template, make a file /etc/apps/hello-splunkjs/appserver/static/js/templates/HelloSplunkJSView.html with the following:

Hellll-lllo Splunk!

See the diff in Github.

Step 2.4: set the view name

Now, lets change the other CHANGEME’s in the view’s Javascript (/etc/apps/hello-splunkjs/appserver/static/js/views/HelloSplunkJSView.js). We are naming the view “HelloSplunkJSView” so change the rest of the CHANGEME’s accordingly.

This will result in:

define([
    "underscore",
    "backbone",
    "splunkjs/mvc",
    "jquery",
    "splunkjs/mvc/simplesplunkview",
    'text!../app/hello-splunkjs/js/templates/HelloSplunkJSView.html',
    "css!../app/hello-splunkjs/css/HelloSplunkJSView.css"
], function(
    _,
    Backbone,
    mvc,
    $,
    SimpleSplunkView,
    Template
){
    // Define the custom view class
    var HelloSplunkJSView = SimpleSplunkView.extend({
        className: "HelloSplunkJSView",
        
        defaults: {
        	
        },
        
        initialize: function() {
        	this.options = _.extend({}, this.defaults, this.options);
        	
        	//this.some_option = this.options.some_option;
        },
        
        render: function () {
        	
        	this.$el.html(_.template(Template, {
        		//'some_option' : some_option
        	}));
        	
        }
    });
    
    return HelloSplunkJSView;
});

See the diff in Github.

Step 2.5: insert the text.js third party library

To make things easy, we are going to use a third-party library called text.js. The nice thing about Splunk views is that you can use the plethora of third-party Javaacript libraries in your apps. It is best to keep third-party libraries in a dedicated directory so that you can easily determine which parts were made by someone else. Let’s put those under /appserver/static/contrib. In the case of our app, the path will be /etc/apps/hello-splunkjs/appserver/static/contrib.

text.js is available from https://github.com/requirejs/text. Put it the app in the path /etc/apps/hello-splunkjs/appserver/static/contrib/text.js. Next, we will need to tell our view where to find text.js by adding a line to require.js’s shim. Put the following at the top of /etc/apps/hello-splunkjs/appserver/static/js/views/HelloSplunkJSView.js:

require.config({
    paths: {
    	text: "../app/hello-splunkjs/contrib/text"
    }
});

See the diff in Github.

Step 3: add to a dashboard

Step 3.1: make the view

We need to make a view that will host the Javascript view we just created. To do this, we will create a simple view that includes an place-holder where the view will render.

To do this, create the following view in /etc/apps/hello-splunkjs/default/data/ui/views/hellosplunkjs.xml:

<?xml version='1.0' encoding='utf-8'?>

<form script="hellosplunkjs.js" >
	<label>Hello SplunkJS</label>
	
	<row>
		<html>
			<div id="placeholder_for_view">This placeholder should be replaced with the content of the view</div>
		</html>
	</row>
</form>

See the diff in Github.

Step 3.2: put the view in the app’s navigation file

Next, make the nav.xml to register the view by making the following file in /etc/apps/hello-splunkjs/default/data/ui/nav/default.xml:

<nav color="#3863A0">
  <view name="hellosplunkjs" default="true" />
</nav>

See the diff in Github.

Restart Splunk and navigate to the view; you should see it with the text “This placeholder should be replaced with the content of the view”.

Step 3.3: wire up the Javascript view to dashboard

Now, we need to wire-up the Javascript view to the dashboard. To do so, make the following file at /etc/apps/hello-splunkjs/appserver/static/hellosplunkjs.js:

require.config({
    paths: {
        hello_splunk_js_view: '../app/hello-splunkjs/js/views/HelloSplunkJSView'
    }
});

require(['jquery','underscore','splunkjs/mvc', 'hello_splunk_js_view', 'splunkjs/mvc/simplexml/ready!'],
		function($, _, mvc, HelloSplunkJSView){
	
    // Render the view on the page
    var helloSplunkJSView = new HelloSplunkJSView({
        el: $('#placeholder_for_view')
    });
    
    // Render the view
    helloSplunkJSView.render();
	
});

This script instantiates an instance of the HelloSplunkJSView and tells it to render in the “placeholder_for_view” element (which was declared in the hellosplunkjs.xml view).

See the diff in Github.

Step 4: add click handlers

Now, lets make something in the view that is interactive (takes input from the user).

Step 4.1: create an HTML element that is clickable

We need to change the template file to include a clickable element. To do this, modify the file /etc/apps/hello-splunkjs/appserver/static/js/templates/HelloSplunkJSView.html with the following:

Hellll-lllo Splunk!
<div class="get-most-recent-event">Get the most recent event in Splunk</div>
<textarea id="most-recent-event"></textarea>

See the diff in Github.

Step 4.2: wire up the clickable element to a function

Next, wire up a click handlers along with a function that will fire when the user clicks the “get-most-recent-event” element. We do this by adding an events attribute that connects the HTML to a function called doGetMostRecentEvent(), which we will create in the next step:

define([
    "underscore",
    "backbone",
    "splunkjs/mvc",
    "jquery",
    "splunkjs/mvc/simplesplunkview",
    'text!../app/hello-splunkjs/js/templates/HelloSplunkJSView.html',
    "css!../app/hello-splunkjs/css/HelloSplunkJSView.css"
], function(
    _,
    Backbone,
    mvc,
    $,
    SimpleSplunkView,
    Template
){
    // Define the custom view class
    var HelloSplunkJSView = SimpleSplunkView.extend({
        className: "HelloSplunkJSView",
        
        events: {
        	"click .get-most-recent-event" : "doGetMostRecentEvent"
        },

See the diff in Github.

Step 4.3: run a search from Javascript

Now, lets add a require statement to import the SearchManager so that we kick off a search. We do this by adding “splunkjs/mvc/searchmanager” to the define statement and assigning the resulting object to “SearchManager” in the function:

define([
    "underscore",
    "backbone",
    "splunkjs/mvc",
    "jquery",
    "splunkjs/mvc/simplesplunkview",
    "splunkjs/mvc/searchmanager",
    'text!../app/hello-splunkjs/js/templates/HelloSplunkJSView.html',
    "css!../app/hello-splunkjs/css/HelloSplunkJSView.css"
], function(
    _,
    Backbone,
    mvc,
    $,
    SimpleSplunkView,
    SearchManager,
    Template
){

See the diff in Github.

Now, let’s add code in the function doGetMostRecentEvent() that will kick off a search and put the most recent event in the view. See below for the created function:

        doGetMostRecentEvent: function(){ 
        	
           // Make a search
            var search = new SearchManager({
                "id": "get-most-recent-event-search",
                "earliest_time": "-1h@h",
                "latest_time": "now",
                "search":'index=_internal OR index=main | head 1 | fields _raw',
                "cancelOnUnload": true,
                "autostart": false,
                "auto_cancel": 90,
                "preview": false
            }, {tokens: true});
            
        	
            search.on('search:failed', function() {
                alert("Search failed");
            }.bind(this));
            
            search.on("search:start", function() {
                console.log("Search started");
            }.bind(this));
            
            search.on("search:done", function() {
                console.log("Search completed");
            }.bind(this));
        	
            // Get a reference to the search results
            var searchResults = search.data("results");
            
            // Process the results of the search when they become available
            searchResults.on("data", function() {
            	$("#most-recent-event", this.$el).val(searchResults.data().rows[0][0]);
            }.bind(this));
            
            // Start the search
            search.startSearch();
            
        },

See the diff in Github.

Restart Splunk and click the text “Get the most recent event in Splunk”; the most recent event should show up in the view when you click the “Get the most recent event in Splunk” text:

most_recent_event

Step 4.4: customize styling

The link we made for getting the raw event doesn’t look like a link. Let’s deploy some styling to make it look clickable. To do this, edit the file /etc/apps/hello-splunkjs/appserver/static/css/HelloSplunkJSView.css with the following:

.get-most-recent-event{
	color: blue;
	text-decoration: underline;
}

This will style the link such that it looks like this:

hello_splunkjs_with_link

See the diff in Github.

Conclusion

There is many more things that you can do with Javascript in Splunk, this is just the start. See dev.splunk.com and Splunk answers if you need more help.

 

One Trackback

  1. […] Creating a Splunk Javascript View (Luke Murphey) […]