030e5c7918433b9d49f0957903332d3dedbac606
[god.git] / lib / god / logger.rb
blob030e5c7918433b9d49f0957903332d3dedbac606
1 module God
2   
3   class Logger < ::Logger
4     SYSLOG_EQUIVALENTS = {:fatal => :crit,
5                           :error => :err,
6                           :warn => :debug,
7                           :info => :debug,
8                           :debug => :debug}
9     
10     attr_accessor :logs
11     
12     def initialize
13       super($stdout)
14       self.logs = {}
15       @mutex = Mutex.new
16       @capture = nil
17     end
18     
19     def start_capture
20       @mutex.synchronize do
21         @capture = StringIO.new
22       end
23     end
24     
25     def finish_capture
26       @mutex.synchronize do
27         cap = @capture.string
28         @capture = nil
29         cap
30       end
31     end
32     
33     def log(watch, level, text)
34       # initialize watch log if necessary
35       self.logs[watch.name] ||= Timeline.new(God::LOG_BUFFER_SIZE_DEFAULT) if watch
36       
37       # push onto capture and timeline for the given watch
38       buf = StringIO.new
39       templog = ::Logger.new(buf)
40       templog.level = Logger::INFO
41       templog.send(level, text % [])
42       @mutex.synchronize do
43         @capture.puts(buf.string) if @capture
44         self.logs[watch.name] << [Time.now, buf.string] if watch
45       end
46       templog.close
47       
48       # send to regular logger
49       self.send(level, text % [])
50       
51       # send to syslog
52       Syslog.send(SYSLOG_EQUIVALENTS[level], text)
53     end
54     
55     def watch_log_since(watch_name, since)
56       # initialize watch log if necessary
57       self.logs[watch_name] ||= Timeline.new(God::LOG_BUFFER_SIZE_DEFAULT)
58       
59       # get and join lines since given time
60       @mutex.synchronize do
61         self.logs[watch_name].select do |x|
62           x.first > since
63         end.map do |x|
64           x[1]
65         end.join
66       end
67     end
68   end
69   
70 end