Skip to content

Instantly share code, notes, and snippets.

@jamesmoriarty
Last active April 29, 2016 19:30
Show Gist options
  • Save jamesmoriarty/9f743c5f130e46fe497d to your computer and use it in GitHub Desktop.
Save jamesmoriarty/9f743c5f130e46fe497d to your computer and use it in GitHub Desktop.
Newrelic Insights Query
require 'net/http'
require 'uri'
require 'json'
module NewRelic
module Insights
class Query
attr_reader :key, :account_id
def initialize(key, account_id)
@key = key
@account_id = account_id
end
def call(nrql)
get uri(URI.encode_www_form(nrql: nrql))
end
private
def uri(query)
URI::HTTPS.build(host: host, path: path, query: query)
end
def get(uri)
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |client|
request = Net::HTTP::Get.new(uri)
request["Accept"] = "application/json"
request["X-Query-Key"] = key
response = client.request(request)
return JSON.parse(response.body, symbolize_names: true)
end
end
def host
"insights-api.newrelic.com"
end
def path
"/v1/accounts/#{account_id}/query"
end
end
end
end
<% content_for :title do %>My super sweet dashboard<% end %>
<div class="gridster">
<ul>
<li data-row="1" data-col="1" data-sizex="1" data-sizey="1">
<div data-id="sessions" data-view="Number" data-title="Current Sessions"></div>
</li>
</ul>
<center><div style="font-size: 12px">Try this: curl -d '{ "auth_token": "YOUR_AUTH_TOKEN", "text": "Hey, Look what I can do!" }' \http://<%=request.host%>:<%=request.port%>/widgets/welcome</div></center>
</div>
SCHEDULER.every '60s', first_in: 0, allow_overlapping: false do |job|
key = ENV.fetch("NEWRELIC_INSIGHTS_QUERY_KEY")
account_id = ENV.fetch("NEWRELIC_ACCOUNT_ID")
nrql = "SELECT uniqueCount(session) FROM PageView SINCE 5 minutes AGO"
json = NewRelic::Insights::Query.new(key, account_id).call(nrql)
count = json.fetch(:results).first.fetch(:uniqueCount)
send_event('sessions', { current: count })
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment