Skip to content

Instantly share code, notes, and snippets.

@gabetax
Last active February 1, 2016 18:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabetax/c49bcefaace7da649f7b to your computer and use it in GitHub Desktop.
Save gabetax/c49bcefaace7da649f7b to your computer and use it in GitHub Desktop.
Pluck values out of JSON logs
#!/usr/bin/env ruby
require 'json'
# Usage:
# head production.log.json | ruby json_pluck.rb time,session,message
# colorize output when going to stdout or if explicitly requested (e.g. `| less -r`)
color = $stdout.tty?
color = true if ARGV.first == '-c' && ARGV.shift
pluck = (ARGV.first || 'time,message').split ','
colors = Hash.new('0').merge({
'fatal' => '41', # Red background
'error' => '31', # Red
'warn' => '33', # Yellow
'info' => '0', # Reset (no formatting)
'debug' => '30;1' # Dark grey
})
while input = $stdin.gets
begin
row = JSON.parse(input)
str = pluck.map { |k| row[k] || 'null' }.join(' ')
if color
puts "\033[#{colors[row['severity']]}m" + str + "\033[0m"
else
puts str
end
# syslogd truncates lines > 4k in length, including their new line characters.
# Recovery would be better, but for now just ignore them.
rescue JSON::ParserError
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment