/
proc_title.rb
59 lines (50 loc) · 1.17 KB
/
proc_title.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
module Metriks::Reporter
class ProcTitle
def initialize(options = {})
@rounding = options[:rounding] || 1
@prefix = options[:prefix] || $0.dup
@interval = options[:interval] || 5
@on_error = options[:on_error] || proc { |ex| }
@metrics = []
end
def add(name, suffix = nil, &block)
@metrics << [ name, suffix, block ]
end
def empty?
@metrics.empty?
end
def start
@thread ||= Thread.new do
loop do
begin
unless @metrics.empty?
title = generate_title
if title && !title.empty?
$0 = "#{@prefix} #{title}"
end
end
rescue Exception => ex
@on_error[ex] rescue nil
end
sleep @interval
end
end
end
def stop
@thread.kill if @thread
@thread = nil
end
def restart
stop
start
end
protected
def generate_title
@metrics.collect do |name, suffix, block|
val = block.call
val = "%.#{@rounding}f" % val if val.is_a?(Float)
"#{name}: #{val}#{suffix}"
end.join(' ')
end
end
end