Skip to content

Instantly share code, notes, and snippets.

@slumos
Forked from entombedvirus/gist:31783
Created December 4, 2008 00:29
Show Gist options
  • Save slumos/31784 to your computer and use it in GitHub Desktop.
Save slumos/31784 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
class Munin
class LogReader
attr_accessor :log_file, :me, :pluginstatedir, :statefile
def initialize(file_name)
@file_name = file_name
@me = File.basename($0)
@pluginstatedir = ENV['MUNIN_PLUGSTATE'] || '/var/lib/munin/plugin-state'
@statefile = File.join(@pluginstatedir, @me)
end
def collect!
File.open(@file_name, "r") do |f|
load_saved_state(f)
process(f)
save_state(f)
end
end
def load_saved_state(log_file)
return unless File.exists?(statefile) && !(state = File.read(statefile)).nil?
pos, last_file_size = Marshal.load(state)
# Check for log rotation
return if File.size(@file_name) < last_file_size
log_file.pos = pos
end
def process(log_file)
# Only subclasses know how to process each type of logfile
puts "NEED IMPLEMENTATION"
end
def save_state(log_file)
File.open(statefile, "w") do |f|
f.write(Marshal.dump([log_file.pos, File.size(log_file)]))
end
end
def print_data
data.each do |k, v|
puts "#{k}.value #{v}"
end
end
def data
[] # Left for subclasses
end
end
class Rails < LogReader
def data
@data ||= Hash.new {|h, k| h[k] = Array.new}
end
def process(log_file)
begin
count = 0
loop do
line = log_file.readline
count += 1
next unless line.match(/^Completed in/)
chunks = line.split(/\s/)
data[:total] << chunks[2].to_f
data[:rendering] << chunks[7].to_f
data[:memcache] << chunks[11].to_f
data[:db] << chunks[14].to_f
end
rescue EOFError
end
puts "Counted #{count} lines"
data.each do |k, v|
data[k] = data[k].inject(0) {|sum, i| sum + i} / data[k].length rescue 0
end
end
def config
puts <<-LABEL
graph_title Rails Response Breakdown
graph_vlabel response time
graph_category Rails
total.label total
rendering.label rendering
db.label db
memcache.label memcache
LABEL
end
end
end
APP = File.basename($0).split('_').first
RAILS_ROOT = "/var/www/apps/#{APP}/current"
RAILS_ENV = File.basename($0).split('_')[1]
log_file = "#{RAILS_ROOT}/log/#{RAILS_ENV}.log"
ALLOWED_COMMANDS = ['config']
rails = Munin::Rails.new("tmp/live.log")
if cmd = ARGV[0] and ALLOWED_COMMANDS.include? cmd then
rails.send(cmd.to_sym)
else
rails.collect!
rails.print_data
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment