Class: Sq::Dbsync::Loggers::Stream

Inherits:
Abstract
  • Object
show all
Defined in:
lib/sq/dbsync/loggers.rb

Overview

Writes timing information to stdout. Thread-safe in that calls to measure from separate threads will execute in parallel but synchronize before writing their output.

Instance Method Summary collapse

Constructor Details

#initialize(out = $stdout) ⇒ Stream

Returns a new instance of Stream.



23
24
25
26
# File 'lib/sq/dbsync/loggers.rb', line 23

def initialize(out = $stdout)
  @mutex   = Mutex.new
  @out     = out
end

Instance Method Details

#log(str, time = Time.now.utc) ⇒ Object



56
57
58
59
# File 'lib/sq/dbsync/loggers.rb', line 56

def log(str, time = Time.now.utc)
  # Synchronize to ensure lines are not interwoven.
  mutex.synchronize { out.puts([time, str].join("\t")) }
end

#log_measurement(time, event, duration, object) ⇒ Object



48
49
50
51
52
53
54
# File 'lib/sq/dbsync/loggers.rb', line 48

def log_measurement(time, event, duration, object)
  log([
    event,
    "%.3f" % duration,
    object
  ].join("\t"), time)
end

#measure(label, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/sq/dbsync/loggers.rb', line 28

def measure(label, &block)
  start_time = Time.now.utc
  log_measurement(start_time, :starting, 0, label)
  ret = nil
  exception = nil
  state = :finished
  begin
    ret = block.call
  rescue => e
    state = :failed
    exception = e
    raise
  ensure
    end_time = Time.now.utc
    log_measurement(end_time, state, end_time - start_time, label)
    log(exception.message) if exception
  end
  ret
end