Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
New Relic Insides Data Parser
#!/usr/bin/env ruby
#
# frozen_string_literal: true
require 'byebug'
require 'json'
require 'csv'
module NewRelicInsides
class Parser
class << self
def parse(*options)
case options.first
when String
file = options.first
valid_file!(file)
new(file).parse
else
raise ArgumentError
end
end
private
def valid_file!(file)
raise ArgumentError, 'Input file is required' unless File.exists?(file)
end
end
def initialize(file)
@data = parse_json!(File.read(file))
end
def parse
parse_total_results!
parse_rows!
self
end
def to_csv
CSV.open('nri_parsed_data.csv', 'wb') do |csv|
csv << ['Dates', headers[:dates]].flatten
csv << ['Totals', headers[:data]].flatten
rows.each { |key, rows| csv << [key, rows.map(&:last)].flatten }
end
puts '=> Success: CSV file is generated'
end
private
attr_reader :json, :headers, :rows
def parse_rows!
@rows = {}
json['facets'].map do |fa|
@rows[parse_worker_name(fa)] = fa['timeSeries'].map { |row| parse_row(row) }
end
@rows
end
def parse_worker_name(data)
data.fetch('name').gsub(/OtherTransaction\/SidekiqJob\//, '')
end
def parse_total_results!
@headers = { dates: [], data: [] }
json['totalResult']['timeSeries'].each do |ts|
date, data = parse_row(ts)
@headers[:dates] << date
@headers[:data] << data
end
end
def parse_row(data)
[parse_date(data), parse_data(data)]
end
def parse_date(data)
Time.at(data.fetch('beginTimeSeconds')).strftime('%m-%d-%Y')
end
def parse_data(data)
data.fetch('results').first.values.last
end
def parse_json!(data)
@json = JSON.parse(data)
end
end
end
NewRelicInsides::Parser.parse(*ARGV).to_csv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.