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