Module: Doable::Helpers::Logging

Included in:
Job
Defined in:
lib/doable/helpers/logging.rb

Instance Method Summary collapse

Instance Method Details

#colorize(text, color, options = {}) ⇒ String

Applies a color (with optional addition settings) to some text

Parameters:

  • text (String)

    The String to be colorized

  • color (Symbol)

    The color to use. Must be one of [ :gray, :red, :green, :yellow, :blue, :magenta, :cyan, :white ]

Returns:

  • (String)


11
12
13
14
15
16
17
18
19
20
# File 'lib/doable/helpers/logging.rb', line 11

def colorize(text, color, options = {})
  background = options[:background] || options[:bg] || false
  style = options[:style].to_sym if options[:style]
  offsets = [ :gray, :red, :green, :yellow, :blue, :magenta, :cyan, :white ]
  styles = [ :normal, :bold, :dark, :italic, :underline, :xx, :xx, :underline, :xx, :strikethrough ]
  start = background ? 40 : 30
  color_code = start + (offsets.index(color) || 8)
  style_code = styles.index(style) || 0
  "\e[#{style_code};#{color_code}m#{text}\e[0m"
end

#log(text, level = :info) ⇒ Object

All logging or writing to STDOUT should happen here (to be threadsafe)



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/doable/helpers/logging.rb', line 23

def log(text, level = :info)
  level = level.to_sym
    
  color, options = case level
  when :info
    [:white, {}]
  when :warn
    [:yellow, {}]
  when :error
    [:red, {:bg => true}]
  when :success
    [:green, {}]
  else
    [:gray, {}]
  end
    
  LOGGING_MUTEX.synchronize { 
    puts "[#{Time.now.strftime('%Y/%m/%d %H:%M:%S')}] #{colorize(text, color, options)}" 
  }
end