Last active
February 1, 2016 18:45
-
-
Save gabetax/c49bcefaace7da649f7b to your computer and use it in GitHub Desktop.
Pluck values out of JSON logs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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