Module: Log

Extended by:
Term::ANSIColor
Defined in:
lib/scout/log.rb,
lib/scout/log/trap.rb,
lib/scout/log/color.rb,
lib/scout/log/progress.rb,
lib/scout/log/fingerprint.rb,
lib/scout/log/progress/util.rb,
lib/scout/log/progress/report.rb

Defined Under Namespace

Classes: ProgressBar

Constant Summary collapse

MUTEX =
Mutex.new
LAST =
"log"
SEVERITY_COLOR =

.collect{|e| “033[#{e}”}

[reset, cyan, green, magenta, blue, yellow, red]
CONCEPT_COLORS =
IndiferentHash.setup({
  :title => magenta,
  :path => blue,
  :input => cyan,
  :value => green,
  :integer => green,
  :negative => red,
  :float => green,
  :waiting => yellow,
  :started => cyan,
  :start => cyan,
  :done => green,
  :error => red,
  :time => cyan,
  :task => yellow,
  :workflow => yellow,
})
HIGHLIGHT =
"\033[1m"
FP_MAX_STRING =
150
FP_MAX_ARRAY =
20
FP_MAX_HASH =
10

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.logfile(file = nil) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/scout/log.rb', line 110

def self.logfile(file=nil)
  if file.nil?
    @@logfile = nil
  else
    case file
    when String
      @@logfile = File.open(file, :mode => 'a')
      @@logfile.sync = true
    when IO, File
      @@logfile = file
    else
      raise "Unkown logfile format: #{file.inspect}"
    end
  end
end

.nocolorObject

Returns the value of attribute nocolor.



134
135
136
# File 'lib/scout/log/color.rb', line 134

def nocolor
  @nocolor
end

.severityObject

Returns the value of attribute severity.



10
11
12
# File 'lib/scout/log.rb', line 10

def severity
  @severity
end

.tty_sizeObject



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/scout/log.rb', line 56

def self.tty_size
  @@tty_size ||= Log.ignore_stderr do
    size = begin
             IO.console.winsize.last
           rescue Exception
             begin
               res = `tput li`
               res = nil if res == ""
               res || ENV["TTY_SIZE"] || 80
             rescue Exception
               ENV["TTY_SIZE"] || 80
             end
           end
    size = size.to_i if String === size
    size
  end
end

Class Method Details

._ignore_stderrObject



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/scout/log/trap.rb', line 64

def self._ignore_stderr
  begin
    File.open('/dev/null', 'w') do |f|
      backup_stderr = STDERR.dup
      STDERR.reopen(f)
      begin
        yield
      ensure
        STDERR.reopen backup_stderr
        backup_stderr.close
      end
    end
  rescue Errno::ENOENT
    yield
  end
end

._ignore_stdoutObject



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/scout/log/trap.rb', line 86

def self._ignore_stdout
  begin
    File.open('/dev/null', 'w') do |f|
      backup_stdout = STDOUT.dup
      STDOUT.reopen(f)
      begin
        yield
      ensure
        STDOUT.reopen backup_stdout
        backup_stdout.close
      end
    end
  rescue Errno::ENOENT
    yield
  end
end

.clear_line(out = STDOUT) ⇒ Object



137
138
139
# File 'lib/scout/log.rb', line 137

def self.clear_line(out = STDOUT)
  out.puts Log.return_line << " " * (Log.tty_size || 80) << Log.return_line unless nocolor
end

.color(color, str = nil, reset = false) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/scout/log/color.rb', line 169

def self.color(color, str = nil, reset = false)
  return str.dup || "" if nocolor

  if (color == :integer || color == :float) && Numeric === str
    color = if str < 0
              :red
            elsif str > 1
              :cyan
            else
              :green
            end
  end

  if color == :status
    color = case str.to_sym
            when :done
              :green
            when :error, :aborted
              :red
            when :waiting, :queued
              :yellow
            when :started, :streamming
              :cyan
            when :start
              :title
            else
              :cyan
            end
  end

  color = SEVERITY_COLOR[color] if Integer === color
  color = CONCEPT_COLORS[color] if CONCEPT_COLORS.include?(color)
  color = Term::ANSIColor.send(color) if Symbol === color and Term::ANSIColor.respond_to?(color)

  str = str.to_s unless str.nil?
  return str if Symbol === color
  color_str = reset ? Term::ANSIColor.reset.dup : ""
  color_str << color if color
  if str.nil?
    color_str
  else
    color_str + str.to_s + Term::ANSIColor.reset
  end
end

.color_stack(stack) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/scout/log.rb', line 276

def self.color_stack(stack)
  stack.collect do |line|
    line = line.sub('`',"'")
    color = :green if line =~ /workflow/
    color = :blue if line =~ /scout-/
    color = :cyan if line =~ /rbbt-/
    if color
      Log.color color, line
    else
      line
    end
  end unless stack.nil?
end

.count_stackObject



332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/scout/log.rb', line 332

def self.count_stack
  if ! $count_stacks
    Log.debug "Counting stacks at: " << caller.first
    return
  end
  $stack_counts ||= {}
  head = $count_stacks_head
  stack = caller[1..head+1]
  stack.reverse.each do |line,i|
    $stack_counts[line] ||= 0
    $stack_counts[line] += 1
  end
end

.debug(message = nil, &block) ⇒ Object



226
227
228
# File 'lib/scout/log.rb', line 226

def self.debug(message = nil, &block)
  log(message, DEBUG, &block)
end

.default_severityObject



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/scout/log.rb', line 21

def self.default_severity
  @@default_severity ||= begin
                           file = File.join(ENV["HOME"], '.scout/etc/log_severity')
                           if File.exist? file
                             File.open(file) do |f|
                               SEVERITY_NAMES.index f.read.strip
                             end
                           else
                             INFO
                           end
                         end
  @@default_severity
end

.deprecated(m) ⇒ Object



270
271
272
273
274
# File 'lib/scout/log.rb', line 270

def self.deprecated(m)
  stack = caller
  warn("DEPRECATED: " << Log.last_caller(stack))
  warn("* " << (m || "").to_s)
end

.down_lines(num = 1) ⇒ Object



129
130
131
# File 'lib/scout/log.rb', line 129

def self.down_lines(num = 1)
  nocolor ? "" : "\033[#{num+1}E"
end

.error(message = nil, &block) ⇒ Object



250
251
252
# File 'lib/scout/log.rb', line 250

def self.error(message = nil, &block)
  log(message, ERROR, &block)
end

.exception(e) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/scout/log.rb', line 254

def self.exception(e)
  return if e.message.include?("NOLOG")
  last_caller = last_caller caller
  message = e.message
  message = Log.fingerprint(message) if String === message && message.length > 1000
  backtrace = e.backtrace || []
  backtrace = [] if message.include?("NOSTACK")
  if ENV["SCOUT_ORIGINAL_STACK"] == 'true'
    error([e.class.to_s, message].compact * ": " )
    error("BACKTRACE [#{Process.pid}]: " << last_caller << "\n" + color_stack(backtrace)*"\n")
  else
    error("BACKTRACE [#{Process.pid}]: " << last_caller << "\n" + color_stack(backtrace.reverse)*"\n")
    error([e.class.to_s, message].compact * ": " )
  end
end

.fingerprint(obj) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/scout/log/fingerprint.rb', line 6

def self.fingerprint(obj)
  return obj.fingerprint if obj.respond_to?(:fingerprint)

  case obj
  when nil
    "nil"
  when TrueClass
    "true"
  when FalseClass
    "false"
  when Symbol
    ":" << obj.to_s
  when String
    if obj.length > FP_MAX_STRING
      digest = Digest::MD5.hexdigest(obj)
      middle = "<...#{obj.length} - #{digest[0..4]}...>"
      s = (FP_MAX_STRING - middle.length) / 2
      "'" << obj.slice(0,s-1) << middle << obj.slice(-s, obj.length )<< "'"
    else 
      "'" << obj << "'"
    end
  when ConcurrentStream
    name = obj.inspect + " " + obj.object_id.to_s
    name += " #{obj.filename}" if obj.filename
    name
  when IO
    (obj.respond_to?(:filename) and obj.filename ) ? "<IO:" + (obj.filename || obj.inspect + rand(100000)) + ">" : obj.inspect + " " + obj.object_id.to_s
  when File
    "<File:" + obj.path + ">"
  when Array
    if (length = obj.length) > FP_MAX_ARRAY
      "[#{length}--" <<  (obj.values_at(0,1, length / 2, -2, -1).collect{|e| fingerprint(e)} * ",") << "]"
    else
      "[" << (obj.collect{|e| fingerprint(e) } * ", ") << "]"
    end
  when Hash
    if obj.length > FP_MAX_HASH
      "H:{"<< fingerprint(obj.keys) << ";" << fingerprint(obj.values) << "}"
    else
      new = "{"
      obj.each do |k,v|
        new << fingerprint(k) << '=>' << fingerprint(v) << ' '
      end
      if new.length > 1
         new[-1] =  "}"
      else
        new << '}'
      end
      new
    end
  when Float
    if obj.abs > 10
      "%.1f" % obj
    elsif obj.abs > 1
      "%.3f" % obj
    else
      "%.6f" % obj
    end
  when Thread
    if obj["name"]
      obj["name"]
    else
      obj.inspect
    end
  else
    obj.to_s
  end
end

.get_level(level) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/scout/log.rb', line 85

def self.get_level(level)
  case level
  when Numeric
    level.to_i
  when String
    begin
      Log.const_get(level.upcase)
    rescue
      Log.exception $!
    end
  when Symbol
    get_level(level.to_s)
  end || 0
end

.high(message = nil, &block) ⇒ Object



238
239
240
# File 'lib/scout/log.rb', line 238

def self.high(message = nil, &block)
  log(message, HIGH, &block)
end

.highlight(str = nil) ⇒ Object



214
215
216
217
218
219
220
221
222
# File 'lib/scout/log/color.rb', line 214

def self.highlight(str = nil)
  if str.nil?
    return "" if nocolor
    HIGHLIGHT
  else
    return str if nocolor
    HIGHLIGHT + str + color(0)
  end
end

.ignore_stderr(&block) ⇒ Object



82
83
84
# File 'lib/scout/log/trap.rb', line 82

def self.ignore_stderr(&block)
  _ignore_stderr &block
end

.ignore_stdout(&block) ⇒ Object



104
105
106
# File 'lib/scout/log/trap.rb', line 104

def self.ignore_stdout(&block)
  _ignore_stdout &block
end

.info(message = nil, &block) ⇒ Object



242
243
244
# File 'lib/scout/log.rb', line 242

def self.info(message = nil, &block)
  log(message, INFO, &block)
end

.last_caller(stack) ⇒ Object



75
76
77
78
79
80
81
82
83
# File 'lib/scout/log.rb', line 75

def self.last_caller(stack)
  line = nil
  pos ||= 0
  while line.nil? or line =~ /scout\/log\.rb/ and stack.any?
    line = stack.shift
  end
  line ||= caller.first
  line.gsub('`', "'")
end

.log(message = nil, severity = MEDIUM, &block) ⇒ Object



192
193
194
195
196
197
198
# File 'lib/scout/log.rb', line 192

def self.log(message = nil, severity = MEDIUM, &block)
  return if severity < self.severity
  message ||= block.call if block_given?
  return if message.nil?
  message = message + "\n" unless message[-1] == "\n"
  self.logn message, severity, &block
end

.log_obj_fingerprint(obj, level, file = $stdout) ⇒ Object



213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/scout/log.rb', line 213

def self.log_obj_fingerprint(obj, level, file = $stdout)
  stack = caller

  line = Log.last_caller stack

  level = Log.get_level level
  name = Log::SEVERITY_NAMES[level] + ": "
  Log.log Log.color(level, name, true) << line, level
  Log.log "", level
  Log.log Log.color(level, "=> ", true) << Log.fingerprint(obj), level
  Log.log "", level
end

.log_obj_inspect(obj, level, file = $stdout) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/scout/log.rb', line 200

def self.log_obj_inspect(obj, level, file = $stdout)
  stack = caller

  line = Log.last_caller stack

  level = Log.get_level level
  name = Log::SEVERITY_NAMES[level] + ": "
  Log.log Log.color(level, name, true) << line, level
  Log.log "", level
  Log.log Log.color(level, "=> ", true) << obj.inspect, level
  Log.log "", level
end

.log_puts(str) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/scout/log.rb', line 155

def self.log_puts(str)
  MUTEX.synchronize do
    if defined?(@@logfile) && @@logfile
      @@logfile.puts str
    else
      begin
        STDERR.puts str
      rescue
      end
    end
  end
end

.log_write(str) ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/scout/log.rb', line 142

def self.log_write(str)
  MUTEX.synchronize do
    if defined?(@@logfile) && @@logfile
      @@logfile.write str
    else
      begin
        STDERR.write str
      rescue IOError
      end
    end
  end
end

.logn(message = nil, severity = MEDIUM, &block) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/scout/log.rb', line 169

def self.logn(message = nil, severity = MEDIUM, &block)
  return if severity < self.severity
  message ||= block.call if block_given?
  return if message.nil?

  time = Time.now.strftime("%m/%d/%y-%H:%M:%S.%L")

  sev_str = severity.to_s

  if ENV["SCOUT_DEBUG_PID"] == "true"
    prefix = time << "["  << Process.pid.to_s << "]" << color(severity) << "["  << sev_str << "]" << color(0)
  else
    prefix = time << color(severity) << "["  << sev_str << "]" << color(0)
  end
  message = "" << highlight << message << color(0) if severity >= INFO
  str = prefix << " " << message.to_s

  log_write str

  Log::LAST.replace "log"
  nil
end

.low(message = nil, &block) ⇒ Object



230
231
232
# File 'lib/scout/log.rb', line 230

def self.low(message = nil, &block)
  log(message, LOW, &block)
end

.medium(message = nil, &block) ⇒ Object



234
235
236
# File 'lib/scout/log.rb', line 234

def self.medium(message = nil, &block)
  log(message, MEDIUM, &block)
end

.no_barObject



9
10
11
12
# File 'lib/scout/log/progress.rb', line 9

def self.no_bar
  @@no_bar = false unless defined?(@@no_bar)
  @@no_bar || ENV["SCOUT_NO_PROGRESS"] == "true"
end

.no_bar=(value) ⇒ Object



5
6
7
# File 'lib/scout/log/progress.rb', line 5

def self.no_bar=(value)
  @@no_bar = value
end

.reset_colorObject



165
166
167
# File 'lib/scout/log/color.rb', line 165

def self.reset_color
  reset
end

.return_lineObject



133
134
135
# File 'lib/scout/log.rb', line 133

def self.return_line
  nocolor ? "" : "\033[1A"
end

.stack(stack) ⇒ Object



318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/scout/log.rb', line 318

def self.stack(stack)
  if ENV["SCOUT_ORIGINAL_STACK"] == 'true'
    log_puts Log.color :magenta, "Stack trace [#{Process.pid}]: " << Log.last_caller(caller)
    color_stack(stack).each do |line|
      log_puts line
    end
  else
    log_puts Log.color :magenta, "Stack trace [#{Process.pid}]: " << Log.last_caller(caller)
    color_stack(stack.reverse).each do |line|
      log_puts line
    end
  end
end

.trap_std(msg = "STDOUT", msge = "STDERR", severity = 0, severity_err = nil) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/scout/log/trap.rb', line 2

def self.trap_std(msg = "STDOUT", msge = "STDERR", severity = 0, severity_err = nil)
  sout, sin = Open.pipe
  soute, sine = Open.pipe
  backup_stderr = STDERR.dup
  backup_stdout = STDOUT.dup
  old_logfile = Log.logfile
  Log.logfile(backup_stderr)

  severity_err ||= severity
  th_log = Thread.new do
    while line = sout.gets
      Log.logn "#{msg}: " + line, severity
    end
  end

  th_loge = Thread.new do
    while line = soute.gets
      Log.logn "#{msge}: " + line, severity_err
    end
  end

  begin
    STDOUT.reopen(sin)
    STDERR.reopen(sine)
    yield
  ensure
    STDERR.reopen backup_stderr
    STDOUT.reopen backup_stdout
    sin.close
    sine.close
    th_log.join
    th_loge.join
    backup_stdout.close
    backup_stderr.close
    Log.logfile = old_logfile
  end
end

.trap_stderr(msg = "STDERR", severity = 0) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/scout/log/trap.rb', line 40

def self.trap_stderr(msg = "STDERR", severity = 0)
  sout, sin = Open.pipe
  backup_stderr = STDERR.dup
  old_logfile = Log.logfile
  Log.logfile(backup_stderr)

  th_log = Thread.new do
    while line = sout.gets
      Log.logn "#{msg}: " + line, severity
    end
  end

  begin
    STDERR.reopen(sin)
    yield
    sin.close
  ensure
    STDERR.reopen backup_stderr
    th_log.join
    backup_stderr.close
    Log.logfile = old_logfile
  end
end

.tsv(tsv, example = false) ⇒ Object



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/scout/log.rb', line 290

def self.tsv(tsv, example = false)
  log_puts Log.color :magenta, "TSV log: " << Log.last_caller(caller).gsub('`',"'")
  log_puts Log.color(:blue, "=> "<< Log.fingerprint(tsv), true)
  log_puts Log.color(:cyan, "=> " << tsv.summary)
  if example && ! tsv.empty?
    key = case example
          when TrueClass, :first, "first"
            tsv.keys.first
          when :random, "random"
            tsv.keys.shuffle.first
          else
            example
          end

    values = tsv[key]
    values = [values] if tsv.type == :flat || tsv.type == :single
    if values.nil?
      log_puts Log.color(:blue, "Key (#{tsv.key_field}) not present: ") + key
    else
      log_puts Log.color(:blue, "Key (#{tsv.key_field}): ") + key
      tsv.fields.zip(values).each do |field,value|
        log_puts Log.color(:magenta, field + ": ") + (Array === value ? value * ", " : value.to_s)
      end
    end
  end
  Log::LAST.replace "log"
end

.uncolor(str) ⇒ Object



161
162
163
# File 'lib/scout/log/color.rb', line 161

def self.uncolor(str)
  "" << Term::ANSIColor.uncolor(str)
end

.up_lines(num = 1) ⇒ Object



125
126
127
# File 'lib/scout/log.rb', line 125

def self.up_lines(num = 1)
  nocolor ? "" : "\033[#{num+1}F\033[2K"
end

.warn(message = nil, &block) ⇒ Object



246
247
248
# File 'lib/scout/log.rb', line 246

def self.warn(message = nil, &block)
  log(message, WARN, &block)
end

.with_severity(level) ⇒ Object



100
101
102
103
104
105
106
107
108
# File 'lib/scout/log.rb', line 100

def self.with_severity(level)
  orig = Log.severity
  begin
    Log.severity = level
    yield
  ensure
    Log.severity = orig
  end
end

.with_stack_counts(head = 10, total = 100) ⇒ Object



346
347
348
349
350
351
352
353
354
355
# File 'lib/scout/log.rb', line 346

def self.with_stack_counts(head = 10, total = 100)
  $count_stacks_head = head
  $count_stacks = true
  $stack_counts = {}
  res = yield
  $count_stacks = false
  Log.debug "STACK_COUNTS:\n" + $stack_counts.sort_by{|line,c| c}.reverse.collect{|line,c| [c, line] * " - "}[0..total] * "\n"
  $stack_counts = {}
  res
end