# Sidekiq Reporter
#
# Emit key statistics about Sidekiq queues to a stream.
#
# Examples:
#
# Log to STDOUT by default:
#
# ruby sidekiq_reporter.rb
#
# Log to a file by passing the path to the first argument
#
# ruby sidekiq_reporter.rb /usr/var/log/sidekiq.log
#
require 'sidekiq/api'
class SidekiqReporter
attr_reader :queues,
:io
DEFAULT_QUEUE_NAMES = ['default', 'high'].freeze
def initialize(io=nil)
@queues = build_queues
@io = io || $stdout
end
def metadata
{
source: "sidekiq"
}
end
def report
queues.each do |q|
io.puts metadata.merge(queue_stats(q)).to_json
end
end
protected
def build_queues
queues = Sidekiq::Queue.all
names = queues.map(&:name)
# ensure default queues are reported
# even if the queues don't exist right now
DEFAULT_QUEUE_NAMES.each do |q|
queues << Sidekiq::Queue.new(q) unless names.include? q
end
queues
end
def queue_stats(queue)
{}.tap do |stats|
stats[:queue] = queue.name
stats[:size] = queue.size
stats[:queuing_latency] = queue.latency
end
end
end
io = File.open(ARGV[0], 'a') if ARGV[0]
io ||= $stdout.dup
SidekiqReporter.new(io).report
io.close