Example Script

The full script example shown here contains all the required elements.

In this example script, the value for some elements are defined as variables inside the script. For example, the elements of the search request such as the logsource and query are defined as variables. Custom scripts should return date field data only in the supported formats for charts to render correctly. Supported formats include yyyy-MM-ddTHH:mm:ssZ and MM/dd/yy HH:mm:ss:SSS Z.

from unity import UnityConnection, get_response_content
from urllib import urlencode
import CommonAppMod

try:
    import json
except ImportError:
    import simplejson as json

import sys
import re
from datetime import datetime, date, time, timedelta
import UnityAppMod

# Create a new Unity connection to the server and login
unity_connection = UnityConnection('https://myhost:9987/Unity/', 'unityadmin',
 'unityadmin')unity_connection.login()


##########################################################
# Calculates the current time, relative time, and forms timestamps
##########################################################
currentTimestamp = datetime.now()

# Currently chosen relative timestamp
newTimestamp = currentTimestamp - UnityAppMod.getLastYear()

# Format the timestamp
currentFormatted = UnityAppMod.formatTimestamp(currentTimestamp)
newFormatted = UnityAppMod.formatTimestamp(newTimestamp)

# Define the logsource for the search
logsource = '"logsources":[{"type":"logSource","name":"/SystemOut"}]' 

# Define the output data
chartdata = []
timeUnit = 'hour'
timeUnitFormat = 'MM-dd HH:mm:ss.SSS Z'

timestamp = '{"timestamp":{"from":"' + newFormatted + '","to":"'
 + currentFormatted + '","dateFormat":"MM/dd/yy HH:mm:ss.SSS Z"}}'

# Parameter defaults
start = 0
results = 1


##########################################################
def getSearchData(query, facet, sortKey, attributes):

    #Search query to be used as content for POST

    body = '{"start":' + str(start) + ',"results":' + str(results) + \
         ',"filter":{"range":' + timestamp + '},' + \
         query + ',' + \
         sortKey + ',' + \
         attributes + ',' + \
         facet
    #print body

    if logsource:
        body = body + ',' + logsource

    body = body + ' }'
    #print body

    # Post the search request
    response = unity_connection.post(
    '/Search', body, content_type='application/json; charset=UTF-8');
    content = get_response_content(response)


    # Convert the response data to JSON
    data = {}
    try:
        data = json.loads(content)
        #print json.dumps(data, sort_keys=False,indent=4,
               separators=(',', ': '))
    except:
        pass
    if 'result' in data:
        result = data['result']
        if 'status' in result and result['status'] == 'failure':
            msg = result['message']
            print >> sys.stderr, msg
            sys.exit(1)

    return data
##########################################################

##########################################################
def getErrorsWarningsVsTime(chartdata):
    # Define the query for the search
    query = '"query":"severity:(W OR E)"'

    # Define the facet to be used for the search
    facet = '"facets":{"dateFacet":{"date_histogram":{"field":"timestamp",
      "interval":"'+ timeUnit + '","outputDateFormat":"'
      + timeUnitFormat + '","nested_facet":
     {"severityFacet":{"terms":{"field":"severity","size":10}}}}}}'

    #Define the sortKey to be used for the search results
    sortKey = '"sortKey":["-timestamp"]'

    # get the facetFields
    facetFields = [
        { "id":"date", "label":"Timestamp", "type":"DATE" },
        { "id":"severity", "label":"severity", "type":"TEXT"},
        { "id":"count", "label":"Count", "type":"LONG"}
    ]
    facetRows = []

    # Define the attributes
    attributes = '"getAttributes":["timestamp","severity"]'

    # do the query
    data = getSearchData(query, facet, sortKey, attributes)

    if 'facetResults' in data:

        # get the facet results
        facetResults = data['facetResults']
        #print json.dumps(facetResults, sort_keys=False,indent=4,
             separators=(',', ': '))

        if 'dateFacet' in facetResults:
            # get the facetRows
            dateFacet = facetResults['dateFacet']
            CommonAppMod.dateSort(dateFacet)
            for dateRow in dateFacet:
                for severityRow in dateRow['nested_facet']['severityFacet']
                      ['counts']:
                    facetRows.append({"date":dateRow['low'], "severity":severityRow
                    ['term'], "count":severityRow['count']} );
                    #print facetRows

    chartdata.append({'id':'ErrorsWarningsVsTime','fields':facetFields,
           'rows':facetRows})
    return chartdata

##########################################################


# Define the timestamp for the search
#timestamp = '{"timestamp":{"from":"' + newFormatted + '","to":"'
  + currentFormatted + '","dateFormat":"MM/dd/yy HH:mm:ss.SSS Z"}}'
 
# Define the logsource for the search
#logsource = '"logsources":[{"type":"logSource","name":"/SystemOut"}]' 
 



getErrorsWarningsVsTime(chartdata)
unity_connection.logout()
#------------------------------------------------------
# Build the final output data JSON
#------------------------------------------------------

# build the chart data
dt = {'data':chartdata}

#Print the JSON to system out
#print( json.dumps(dt, sort_keys=False,indent=4, separators=(',', ': ')))
print json.dumps(dt, sort_keys=False,indent=4, separators=(',', ': '))