Class: Chandler::Logger

Inherits:
Object
  • Object
show all
Defined in:
lib/chandler/logger.rb

Overview

Similar to Ruby’s standard Logger, but automatically removes ANSI color from the logged messages if stdout and stderr do not support it.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stderr: $stderr, stdout: $stdout) ⇒ Logger

Returns a new instance of Logger.



11
12
13
14
15
# File 'lib/chandler/logger.rb', line 11

def initialize(stderr: $stderr, stdout: $stdout)
  @stderr = stderr
  @stdout = stdout
  @color_enabled = nil
end

Instance Attribute Details

#stderrObject

Returns the value of attribute stderr.



9
10
11
# File 'lib/chandler/logger.rb', line 9

def stderr
  @stderr
end

#stdoutObject

Returns the value of attribute stdout.



9
10
11
# File 'lib/chandler/logger.rb', line 9

def stdout
  @stdout
end

Instance Method Details

#benchmark(message) ⇒ Object

Logs a message to stdout, runs the given block, and then prints the time it took to run the block.



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/chandler/logger.rb', line 31

def benchmark(message)
  start = Time.now
  print(stdout, "#{message} ")
  result = yield
  duration = Time.now - start
  info("".green + format(" %0.3fs", duration).gray)
  result
rescue
  info("".red)
  raise
end

#error(message) ⇒ Object

Logs a message to stderr. Unless otherwise specified, the message will be printed in red.



19
20
21
22
# File 'lib/chandler/logger.rb', line 19

def error(message)
  message = message.red unless message.color?
  puts(stderr, message)
end

#info(message) ⇒ Object

Logs a message to stdout.



25
26
27
# File 'lib/chandler/logger.rb', line 25

def info(message)
  puts(stdout, message)
end