class Chandler::Logger

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

Attributes

stderr[RW]
stdout[RW]

Public Class Methods

new(stderr: $stderr, stdout: $stdout) click to toggle source
# File lib/chandler/logger.rb, line 11
def initialize(stderr: $stderr, stdout: $stdout)
  @stderr = stderr
  @stdout = stdout
  @color_enabled = nil
end

Public Instance Methods

benchmark(message) { || ... } click to toggle source

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

# 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) click to toggle source

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

# File lib/chandler/logger.rb, line 19
def error(message)
  message = message.red unless message.color?
  puts(stderr, message)
end
info(message) click to toggle source

Logs a message to stdout.

# File lib/chandler/logger.rb, line 25
def info(message)
  puts(stdout, message)
end

Private Instance Methods

color_enabled?() click to toggle source
# File lib/chandler/logger.rb, line 55
def color_enabled?
  @color_enabled = determine_color_support if @color_enabled.nil?
  @color_enabled
end
determine_color_support() click to toggle source
# File lib/chandler/logger.rb, line 60
def determine_color_support
  if ENV["CLICOLOR_FORCE"] == "1"
    true
  elsif ENV["TERM"] == "dumb"
    false
  else
    tty?(stdout) && tty?(stderr)
  end
end
print(io, message) click to toggle source
puts(io, message) click to toggle source
# File lib/chandler/logger.rb, line 50
def puts(io, message)
  message = message.strip_color unless color_enabled?
  io.puts(message)
end
tty?(io) click to toggle source
# File lib/chandler/logger.rb, line 70
def tty?(io)
  io.respond_to?(:tty?) && io.tty?
end