Module: DebugTrace

Defined in:
lib/debugtrace.rb,
lib/debugtrace/version.rb

Defined Under Namespace

Classes: PrintOptions

Constant Summary collapse

VERSION =
'0.1.0'
@@AUTHOR =

class Error < StandardError; end

'Masato Kokubo <masatokokubo@gmail.com>'
@@config =

Configuration values

nil
@@thread_mutex =

A Mutex for thread safety

Mutex.new
@@state_hash =

Hash (int: State) of thread id to a trace state

{}
@@before_thread_id =

def self.get_frame_summary(limit)

begin
  raise 'RuntimeError'
rescue => e
  return caller_locations(limit: limit).first
end
return nil

end

nil
@@last_log_buff =

The last output content

nil
@@reflected_objects =

Reflected objects

[]
@@logger =

The logger used by DebugTrace-py

nil
@@DO_NOT_OUTPUT =
'Do not output'

Class Method Summary collapse

Class Method Details

.configObject



23
24
25
# File 'lib/debugtrace.rb', line 23

def self.config
  return @@config
end

.current_stateObject



99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/debugtrace.rb', line 99

def self.current_state
  thread_id = Thread.current.object_id

  if @@state_hash.key?(thread_id)
    state = @@state_hash[thread_id]
  else
    state = State.new(thread_id)
    @@state_hash[thread_id] = state
  end

  state
end

.enterObject



592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
# File 'lib/debugtrace.rb', line 592

def self.enter
  return unless @@config.enabled?
  Mutex.new.synchronize do
    print_start

    state = current_state

  # frame_summary = get_frame_summary(4)
    location = caller_locations(3, 3)[0]
    name     = location != nil ? location.base_label : ''
    filename = location != nil ? File.basename(location.absolute_path) : ''
    lineno   = location != nil ? location.lineno : 0

  # parent_frame_summary = get_frame_summary(5)
    parent_location = caller_locations(4, 4)[0]
    parent_name     = parent_location != nil ? parent_location.base_label : ''
    parent_filename = parent_location != nil ? File.basename(parent_location.absolute_path) : ''
    parent_lineno   = parent_location != nil ? parent_location.lineno : 0

    indent_string = get_indent_string(state.nest_level, 0)
    if state.nest_level < state.previous_nest_level || @@last_log_buff.multi_lines?
      @@logger.print(indent_string) # Empty Line
    end

    @@last_log_buff = LogBuffer.new(@@config.maximum_data_output_width)
    @@last_log_buff.no_break_append(
      @@config.enter_format % [name, filename, lineno, parent_name, parent_filename, parent_lineno]
    )
    @@last_log_buff.line_feed
    @@logger.print(indent_string + @@last_log_buff.lines[0].log)

    state.up_nest
  end
end

.get_indent_string(nest_level, data_nest_level) ⇒ Object



112
113
114
115
116
# File 'lib/debugtrace.rb', line 112

def self.get_indent_string(nest_level, data_nest_level)
  indent_str = @@config.indent_string * [[0, nest_level].max, @@config.maximum_indents].min
  data_indent_str = @@config.data_indent_string * [[0, data_nest_level].max, @@config.maximum_indents].min
  indent_str + data_indent_str
end

.get_simple_type_name(value_type, nest) ⇒ Object



479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/debugtrace.rb', line 479

def self.get_simple_type_name(value_type, nest)
  type_name = nest == 0 ? value_type.to_s : value_type.name
  if type_name.start_with?("<Class '")
    type_name = type_name[8..-1]
  elsif type_name.start_with?("<Enum '")
    type_name = 'enum ' + type_name[7..-1]
  end
  if type_name.end_with?("'>")
    type_name = type_name[0..-3]
  end

  base_names = value_type.ancestors.reject { |base| base == Object }
  base_names = base_names.map { |base| get_simple_type_name(base, nest + 1) }

  if base_names.any?
    type_name += '(' + base_names.join(', ') + ')'
  end

  return type_name
end

.get_type_name(value, count = -1)) ⇒ Object



461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/debugtrace.rb', line 461

def self.get_type_name(value, count = -1)
  value_type = value.class
  type_name = get_simple_type_name(value.class, 0)
  if ['Array', 'Hash', 'Set', 'Tuple'].include?(type_name)
    type_name = ''
  end

  if count >= @@config.minimum_output_count
    type_name += ' ' unless type_name.empty?
    type_name += @@config.count_format % count
  end

  if !type_name.empty?
    type_name = "(#{type_name})"
  end
  return type_name
end

.has_str_repr_method(value) ⇒ Object



500
501
502
503
504
505
506
507
508
509
# File 'lib/debugtrace.rb', line 500

def self.has_str_repr_method(value)
  begin
    members = value.methods
    has_str = members.include?(:to_s)
    has_repr = members.include?(:inspect)
    return has_str, has_repr
  rescue
    return false, false
  end
end

.initialize(config_path = './debugtrace.yml') ⇒ Object



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
# File 'lib/debugtrace.rb', line 45

def self.initialize(config_path = './debugtrace.yml')
  @@config = Config.new(config_path)

  @@last_log_buff = LogBuffer.new(@@config.maximum_data_output_width)

  # Decide the logger class
  case @@config.logger_name.downcase
  when 'stdout'
    @@logger = StdOutLogger.new(@@config)
  when 'stderr'
    @@logger = StdErrLogger.new(@@config)
  when 'logger'
    @@logger = LoggerLogger.new(@@config)
  when /^file:/
    @@logger = FileLogger.new(@@config)
  else
    Pr._print("debugtrace: (#{@@config.config_path}) logger = #{@@config.logger_name} is unknown", STDERR)
  end

  if @@config.enabled?
    ruby_version = RUBY_VERSION
    @@logger.print("DebugTrace-rb #{DebugTrace::VERSION} on Ruby #{ruby_version}")
    @@logger.print("  config file path: #{@@config.config_path}")
    @@logger.print("  logger: #{@@logger}")
  end
end

.last_print_stringObject



655
656
657
658
659
660
661
662
663
664
665
# File 'lib/debugtrace.rb', line 655

def self.last_print_string
  lines = @@last_log_buff.lines
  buff_string = lines.map { |line| _config.data_indent_string * line[0] + line[1] }.join("\n")

  state = nil
  Mutex.new.synchronize do
    state = current_state
  end

  "#{get_indent_string(state.nest_level, 0)}#{buff_string}"
end

.leaveObject



627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
# File 'lib/debugtrace.rb', line 627

def self.leave
  return unless @@config.enabled?
  
  Mutex.new.synchronize do
    print_start

    state = current_state

    location = caller_locations(3, 3)[0]
    name = location.base_label
    filename = File.basename(location.absolute_path)
    lineno = location.lineno

    if @@last_log_buff.multi_lines?
      @@logger.print(get_indent_string(state.nest_level, 0)) # Empty Line
    end

    time = Time.now.utc - state.down_nest

    @@last_log_buff = LogBuffer.new(@@config.maximum_data_output_width)
    @@last_log_buff.no_break_append(
      @@config.leave_format % [name, filename, lineno, time]
    )
    @@last_log_buff.line_feed
    @@logger.print(get_indent_string(state.nest_level, 0) + @@last_log_buff.lines[0].log)
  end
end


536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/debugtrace.rb', line 536

def self.print(name, value = @@DO_NOT_OUTPUT, force_reflection: false,
          output_private: false, output_method: false,
          minimum_output_count: -1, minimum_output_length: -1,
          collection_limit: -1, bytes_limit: -1,
          string_limit: -1, reflection_nest_limit: -1)

  return value unless @@config.enabled?

  Mutex.new.synchronize do
    print_start

    state = current_state
    @@reflected_objects.clear

    last_multi_lines = @@last_log_buff.multi_lines?

    if value.equal? @@DO_NOT_OUTPUT
      # without value
      @@last_log_buff = LogBuffer.new(@@config.maximum_data_output_width)
      @@last_log_buff.no_break_append(name)
    else
      # with value
      print_options = PrintOptions.new(
        force_reflection, output_private, output_method,
        minimum_output_count, minimum_output_length,
        collection_limit, bytes_limit, string_limit, reflection_nest_limit
      )
      @@last_log_buff = to_string(name, value, print_options)
    end

    # append print suffix
  # frame_summary = get_frame_summary(3)
    location = caller_locations(3, 3)[0]
    name     = location != nil ? location.base_label : ''
    filename = location != nil ? File.basename(location.absolute_path) : ''
    lineno   = location != nil ? location.lineno : 0

    @@last_log_buff.no_break_append(
      @@config.print_suffix_format % [name, filename, lineno]
    )

    @@last_log_buff.line_feed

    if last_multi_lines || @@last_log_buff.multi_lines?
      @@logger.print(get_indent_string(state.nest_level, 0)) # Empty Line
    end

    @@last_log_buff.lines.each do |line|
      @@logger.print(get_indent_string(state.nest_level, line.nest_level) + line.log)
    end
  end

  return value
end


522
523
524
525
526
527
528
529
530
531
532
# File 'lib/debugtrace.rb', line 522

def self.print_start
  thread = Thread.current
  thread_id = thread.object_id
  if thread_id != @@before_thread_id
    # Thread changing
    @@logger.print('')
    @@logger.print(@@config.thread_boundary_format % [thread.name, thread.object_id])
    @@logger.print('')
    @@before_thread_id = thread_id
  end
end

.to_string(name, value, print_options) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/debugtrace.rb', line 118

def self.to_string(name, value, print_options)
  buff = LogBuffer.new(@@config.maximum_data_output_width)
  
  separator = ''
  unless name.empty?
    buff.append(name)
    separator = @@config.varname_value_separator
  end

  case value
  when nil
    # None
    buff.no_break_append(separator).append('nil')
  when String
    # String
    value_buff = to_string_str(value, print_options)
    buff.append_buffer(separator, value_buff)
  when Integer, Float, Date, Time, DateTime
    # int, float, Date, Time, DateTime
    buff.no_break_append(separator).append(value.to_s)
  when Array, Set, Hash
    # list, set, tuple, dict
    value_buff = to_string_iterable(value, print_options)
    buff.append_buffer(separator, value_buff)
  else
    has_str, has_repr = has_str_repr_method(value)
    value_buff = LogBuffer.new(@@config.maximum_data_output_width)
    if !print_options.force_reflection && (has_str || has_repr)
      # has to_s or inspect method
      if has_repr
        value_buff.append('inspect(): ')
        value_buff.no_break_append(value.inspect)
      else
        value_buff.append('to_s(): ')
        value_buff.no_break_append(value.to_s)
      end
      buff.append_buffer(separator, value_buff)
    else
      # use reflection
      if @@reflected_objects.any? { |obj| value.equal?(obj) }
        # cyclic reference
        value_buff.no_break_append(@@config.cyclic_reference_string)
      elsif @@reflected_objects.length > print_options.reflection_nest_limit
        # over reflection level limitation
        value_buff.no_break_append(@@config.limit_string)
      else
        @@reflected_objects.push(value)
        value_buff = to_string_reflection(value, print_options)
        @@reflected_objects.pop
      end
      buff.append_buffer(separator, value_buff)
    end
  end
  
  buff
end

.to_string_bytes(value, print_options) ⇒ Object



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/debugtrace.rb', line 239

def self.to_string_bytes(value, print_options)
  bytes_length = value.length
  buff = LogBuffer.new(@@config.maximum_data_output_width)
  buff.no_break_append('(')
  
  if value.is_a?(String)
    buff.no_break_append('bytes')
  elsif value.is_a?(Array)
    buff.no_break_append('bytearray')
  end

  if bytes_length >= @@config.minimum_output_length
    buff.no_break_append(' ')
    buff.no_break_append(sprintf(@@config.length_format, bytes_length))
  end

  buff.no_break_append(') [')

  multi_lines = bytes_length >= @@config.bytes_count_in_line

  if multi_lines
    buff.line_feed
    buff.up_nest
  end

  chars = ''
  count = 0
  value.each_byte do |element|
    if count != 0 && count % @@config.bytes_count_in_line == 0
      if multi_lines
        buff.no_break_append('| ')
        buff.no_break_append(chars)
        buff.line_feed
        chars = ''
      end
    end
    if count >= print_options.bytes_limit
      buff.no_break_append(@@config.limit_string)
      break
    end
    buff.no_break_append(sprintf('%02X ', element))
    chars += (element >= 0x20 && element <= 0x7E) ? element.chr : '.'
    count += 1
  end

  if multi_lines
    # padding
    full_length = 3 * @@config.bytes_count_in_line
    current_length = buff.length
    current_length = full_length if current_length == 0
    buff.no_break_append(' ' * (full_length - current_length))
  end
  buff.no_break_append('| ')
  buff.no_break_append(chars)

  if multi_lines
    buff.line_feed
    buff.down_nest
  end
  buff.no_break_append(']')

  return buff
end

.to_string_iterable(values, print_options) ⇒ Object



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/debugtrace.rb', line 369

def self.to_string_iterable(values, print_options)
  open_char = '{'  # set, frozenset, dict
  close_char = '}'

  if values.is_a?(Array)
    # list
    open_char = '['
    close_char = ']'
  elsif values.is_a?(Tuple)
    # tuple
    open_char = '('
    close_char = ')'
  end

  buff = LogBuffer.new(@@config.maximum_data_output_width)
  buff.append(_get_type_name(values, values.length))
  buff.no_break_append(open_char)

  body_buff = to_string_iterable_body(values, print_options)
  if open_char == '(' && values.length == 1
    # A tuple with 1 element
    body_buff.no_break_append(',')
  end

  multi_lines = body_buff.multi_lines? || buff.length + body_buff.length > @@config.maximum_data_output_width

  if multi_lines
    buff.line_feed
    buff.up_nest
  end

  buff.append_buffer('', body_buff)

  if multi_lines
    buff.line_feed
    buff.down_nest
  end

  buff.no_break_append(close_char)

  return buff
end

.to_string_iterable_body(values, print_options) ⇒ Object



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/debugtrace.rb', line 412

def self.to_string_iterable_body(values, print_options)
  buff = LogBuffer.new(@@config.maximum_data_output_width)

  multi_lines = false
  index = 0

  values.each do |element|
    if index > 0
      buff.no_break_append(', ')
    end

    if index >= print_options.collection_limit
      buff.append(@@config.limit_string)
      break
    end

    element_buff = LogBuffer.new(@@config.maximum_data_output_width)
    if values.is_a?(Hash)
      # dictionary
      element_buff = to_string_key_value(element, values[element], print_options)
    else
      # list, set, frozenset, or tuple
      element_buff = to_string('', element, print_options)
    end

    if index > 0 && (multi_lines || element_buff.multi_lines?)
      buff.line_feed
    end
    buff.append_buffer('', element_buff)

    multi_lines = element_buff.multi_lines?
    index += 1
  end

  if values.is_a?(Hash) && values.empty?
    buff.no_break_append(':')
  end

  return buff
end

.to_string_key_value(key, value, print_options) ⇒ Object



453
454
455
456
457
458
459
# File 'lib/debugtrace.rb', line 453

def self.to_string_key_value(key, value, print_options)
  buff = LogBuffer.new(@@config.maximum_data_output_width)
  key_buff = to_string('', key, print_options)
  value_buff = to_string('', value, print_options)
  buff.append_buffer('', key_buff).append_buffer(@@config.key_value_separator, value_buff)
  return buff
end

.to_string_reflection(value, print_options) ⇒ Object



303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/debugtrace.rb', line 303

def self.to_string_reflection(value, print_options)
  buff = LogBuffer.new(@@config.maximum_data_output_width)

  buff.append(_get_type_name(value))

  body_buff = to_string_reflection_body(value, print_options)

  multi_lines = body_buff.multi_lines? || buff.length + body_buff.length > @@config.maximum_data_output_width

  buff.no_break_append('{')
  if multi_lines
    buff.line_feed
    buff.up_nest
  end

  buff.append_buffer('', body_buff)

  if multi_lines
    buff.line_feed if buff.length > 0
    buff.down_nest
  end
  buff.no_break_append('}')

  return buff
end

.to_string_reflection_body(value, print_options) ⇒ Object



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/debugtrace.rb', line 329

def self.to_string_reflection_body(value, print_options)
  buff = LogBuffer.new(@@config.maximum_data_output_width)

  members = []
  begin
    base_members = value.methods(false).map { |m| [m, value.send(m)] }
    members = base_members.select do |m|
      name, _ = m
      !name.start_with?('__') || !name.end_with?('__') && 
      (print_options.output_method || !value.method(name).owner.nil?) && 
      (print_options.output_private || !name.start_with?('_'))
    end
  rescue => ex
    buff.append(ex.to_s)
    return buff
  end

  multi_lines = false
  index = 0
  members.each do |member|
    if index > 0
      buff.no_break_append(', ')
    end

    name, value = member
    member_buff = LogBuffer.new(@@config.maximum_data_output_width)
    member_buff.append(name)
    member_buff.append_buffer(@@config.key_value_separator, to_string('', value, print_options))
    if index > 0 && (multi_lines || member_buff.multi_lines?)
      buff.line_feed
    end
    buff.append_buffer('', member_buff)

    multi_lines = member_buff.multi_lines?
    index += 1
  end

  return buff
end

.to_string_str(value, print_options) ⇒ Object



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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/debugtrace.rb', line 175

def self.to_string_str(value, print_options)
  has_single_quote = false
  has_double_quote = false
  single_quote_buff = LogBuffer.new(@@config.maximum_data_output_width)
  double_quote_buff = LogBuffer.new(@@config.maximum_data_output_width)
  
  if value.length >= @@config.minimum_output_length
    single_quote_buff.no_break_append("(")
    single_quote_buff.no_break_append(sprintf(@@config.length_format, value.length))
    single_quote_buff.no_break_append(")")
    double_quote_buff.no_break_append("(")
    double_quote_buff.no_break_append(sprintf(@@config.length_format, value.length))
    double_quote_buff.no_break_append(")")
  end
  
  single_quote_buff.no_break_append("'")
  double_quote_buff.no_break_append('"')
  
  count = 1
  value.each_char do |char|
    if count > print_options.string_limit
      single_quote_buff.no_break_append(@@config.limit_string)
      double_quote_buff.no_break_append(@@config.limit_string)
      break
    end
    case char
    when "'"
      single_quote_buff.no_break_append("\\'")
      double_quote_buff.no_break_append(char)
      has_single_quote = true
    when '"'
      single_quote_buff.no_break_append(char)
      double_quote_buff.no_break_append("\\\"")
      has_double_quote = true
    when '\\'
      single_quote_buff.no_break_append('\\\\')
      double_quote_buff.no_break_append('\\\\')
    when '\n'
      single_quote_buff.no_break_append('\\n')
      double_quote_buff.no_break_append('\\n')
    when '\r'
      single_quote_buff.no_break_append('\\r')
      double_quote_buff.no_break_append('\\r')
    when '\t'
      single_quote_buff.no_break_append('\\t')
      double_quote_buff.no_break_append('\\t')
    when ("\0".."\37").include?(char)
      num_str = format('%02X', char.ord)
      single_quote_buff.no_break_append("\\x" + num_str)
      double_quote_buff.no_break_append("\\x" + num_str)
    else
      single_quote_buff.no_break_append(char)
      double_quote_buff.no_break_append(char)
    end
    count += 1
  end
  
  double_quote_buff.no_break_append('"')
  single_quote_buff.no_break_append("'")
  
  return double_quote_buff if has_single_quote && !has_double_quote
  single_quote_buff
end