Module: DebugTrace

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

Overview

The main module of DebugTrace-rb.

Defined Under Namespace

Classes: PrintOptions

Constant Summary collapse

VERSION =
'1.3.2'
@@no_reflection_classes =
[
  FalseClass, TrueClass, Integer, Float, Rational, Complex, Range, Regexp,
]
@@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 =

The before thread id

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



26
27
28
# File 'lib/debugtrace.rb', line 26

def self.config
  return @@config
end

.current_stateState

Returns the current state.

Returns:

  • (State)

    the current state



122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/debugtrace.rb', line 122

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

  return state
end

.enterObject

Prints the start of the method.



606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/debugtrace.rb', line 606

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

    state = current_state
    location = Location.new(caller_locations(3, 3)[0])
    parent_location = Location.new(caller_locations(4, 4)[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.data_output_width)
    @@last_log_buff.no_break_append(
      format(@@config.enter_format,
        location.name, location.path, location.lineno,
        parent_location.name, parent_location.path, parent_location.lineno)
    )
    @@last_log_buff.line_feed
    @@logger.print(indent_string + @@last_log_buff.lines[0].log)

    state.up_nest
  end
  return nil
end

.get_indent_string(nest_level, data_nest_level) ⇒ Sring

Returns the current indent string.

Parameters:

  • nest_level (Integer)

    the code nesting level

  • data_nest_level (Integer)

    the data nesting level

Returns:

  • (Sring)

    the current indent string



140
141
142
143
144
# File 'lib/debugtrace.rb', line 140

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
  return indent_str + data_indent_str
end

.get_type_name(value, size, print_options) ⇒ Object

Returns the type name.

Parameters:

  • value (Object)

    the value

  • size (Object)

    the size of Array, Set or Hash

  • print_options (PrintOptions)

    the print options



519
520
521
522
523
524
525
526
527
528
# File 'lib/debugtrace.rb', line 519

def self.get_type_name(value, size, print_options)
  type_name = value.class.to_s
  type_name = '' if %w[Array Hash Set].include?(type_name)

  if size >= print_options.minimum_output_size
    type_name += @@config.size_format % size
  end

  return type_name
end

.initializeObject

Initialize this class



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/debugtrace.rb', line 54

def self.initialize()
  config_path = ENV['DEBUGTRACE_CONFIG']
  if config_path == nil || config_path.empty?
    config_path = './debugtrace.yml'
  end

  @@config = Config.new(config_path)

  @@last_log_buff = LogBuffer.new(@@config.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 'rubylogger'
    @@logger = RubyLogger.new(@@config)
  when 'file'
    @@logger = FileLogger.new(@@config)
  else
    @@logger = StdErrLogger.new(@@config)
    @@logger.print("DebugTrace-rb: logger = #{@@config.logger_name} is unknown. (#{@@config.config_path}) \n")
  end

  return unless @@config.enabled?

  @@logger.print("DebugTrace-rb #{DebugTrace::VERSION} on Ruby #{RUBY_VERSION} / #{RUBY_PLATFORM}")
  @@logger.print("  config file: #{config_path}")
  @@logger.print("  logger: #{@@logger}")
end

.last_print_stringObject

Returns the last print string.



663
664
665
666
667
668
669
670
671
672
673
# File 'lib/debugtrace.rb', line 663

def self.last_print_string
  lines = @@last_log_buff.lines
  buff_string = lines.map { |line| @@config.data_indent_string * line.nest_level + line.log }.join("\n")

  state = nil
  @@thread_mutex.synchronize do
    state = current_state
  end

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

.leave(return_value = nil) ⇒ Object

Prints the end of the method.

Parameters:

  • [Object] (Hash)

    a customizable set of options

Returns:

  • (Object)

    return_value if specified, otherwise nil



638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
# File 'lib/debugtrace.rb', line 638

def self.leave(return_value = nil)
  @@thread_mutex.synchronize do
    print_start
    return return_value unless @@config.enabled?

    state = current_state
    location = Location.new(caller_locations(3, 3)[0])

    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) * 1000 # milliseconds <- seconds

    @@last_log_buff = LogBuffer.new(@@config.data_output_width)
    @@last_log_buff.no_break_append(
      format(@@config.leave_format, location.name, location.path, location.lineno, time)
    )
    @@last_log_buff.line_feed
    @@logger.print(get_indent_string(state.nest_level, 0) + @@last_log_buff.lines[0].log)
  end
  return return_value
end

Prints the message or the value.

Parameters:

  • name (String)

    a message if the value is not specified, otherwise the value name

  • string_as_bytes (TrueClass, FalseClass) (defaults to: false)

    print string as byte array if true

  • value (Hash) (defaults to: @@DO_NOT_OUTPUT)

    a customizable set of options

  • reflection (Hash) (defaults to: false)

    a customizable set of options

  • minimum_output_size (Hash) (defaults to: -1,)

    a customizable set of options

  • minimum_output_length (Hash) (defaults to: -1,)

    a customizable set of options

  • output_size_limit (Hash) (defaults to: -1,)

    a customizable set of options

  • output_length_limit (Hash) (defaults to: -1,)

    a customizable set of options

  • reflection_limit (Hash) (defaults to: -1))

    a customizable set of options

Options Hash (value):

  • the (Object)

    value

Options Hash (reflection:):

  • use (TrueClass, FalseClass)

    reflection if true

Options Hash (minimum_output_size:):

  • the (Integer)

    minimum value to output the number of elements for Array and Hash (overrides debugtarace.yml value)

Options Hash (minimum_output_length:):

  • the (Integer)

    minimum value to output the length of String and byte array (overrides debugtarace.yml value)

Options Hash (output_size_limit:):

  • Output (Integer)

    limit of collection elements (overrides debugtarace.yml value)

Options Hash (output_length_limit:):

  • the (Integer)

    limit value of characters for string to output (overrides debugtarace.yml value)

Options Hash (reflection_limit:):

  • reflection (Integer)

    limits when using reflection (overrides debugtarace.yml value)



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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
# File 'lib/debugtrace.rb', line 559

def self.print(name, value = @@DO_NOT_OUTPUT,
    reflection: false, string_as_bytes: false, minimum_output_size: -1, minimum_output_length: -1,
    output_size_limit: -1, output_length_limit: -1, reflection_limit: -1)
  @@thread_mutex.synchronize do
    print_start
    return value unless @@config.enabled?

    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.data_output_width)
      @@last_log_buff.no_break_append(name)
    else
      # with value
      print_options = PrintOptions.new(
        reflection, string_as_bytes, minimum_output_size, minimum_output_length,
        output_size_limit, output_length_limit, reflection_limit
      )
      @@last_log_buff = to_string(name, value, print_options)
    end

    # append print suffix
    location = Location.new(caller_locations(3, 3)[0])

    @@last_log_buff.no_break_append(
      format(@@config.print_suffix_format, location.name, location.path, location.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.equal? @@DO_NOT_OUTPUT ? nil : value
end

Called at the start of the print method.



531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
# File 'lib/debugtrace.rb', line 531

def self.print_start
  if @@config == nil
    initialize
  end
  return unless @@config.enabled?

  thread = Thread.current
  thread_id = thread.object_id
  return unless thread_id != @@before_thread_id

  # Thread changing
  @@logger.print('')
  @@logger.print(format(@@config.thread_boundary_format, thread.name, thread_id))
  @@logger.print('')
  @@before_thread_id = thread_id
end

.to_string(name, value, print_options) ⇒ Object

Returns a string representation of the variable contents.

Parameters:

  • name (String)

    the variable name

  • value (Object)

    the value

  • print_options (PrintOptions)

    the print options



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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
213
214
215
216
217
218
219
220
221
222
# File 'lib/debugtrace.rb', line 151

def self.to_string(name, value, print_options)
  buff = LogBuffer.new(@@config.data_output_width)

  unless name.empty?
    buff.append(name).no_break_append(@@config.varname_value_separator)
  end

  if @@no_reflection_classes.include?(value.class)
    buff.append(value.to_s)
  else
    case value
    when nil
      buff.append('nil')
    when Symbol
      buff.append(':').no_break_append(value.name)
    when Class
      buff.append(value.name).no_break_append(' class')
    when Module
      buff.append(value.name).no_break_append(' module')
    when String
      value_buff = nil
      if print_options.string_as_bytes && value.encoding == Encoding::ASCII_8BIT
        value_buff = to_string_bytes(value, print_options)
      else
        begin
          value_buff = to_string_str(value, print_options)
        rescue
          value_buff = to_string_bytes(value, print_options)
        end
      end
      buff.append_buffer(value_buff)
    when DateTime, Time
      buff.append(value.strftime('%Y-%m-%d %H:%M:%S.%L%:z'))
    when Date
      buff.append(value.strftime('%Y-%m-%d'))
    when Dir, File
      buff.append(value.class.name)
      buff.append_buffer(to_string_str(value.path, print_options))
    when Array, Set, Hash
      value_buff = to_string_enumerable(value, print_options)
      buff.append_buffer(value_buff)
    else
      reflection = print_options.reflection || value.class.superclass == Struct

      begin
        to_s_string = reflection ? '' : value.to_s 
        if reflection || to_s_string.start_with?('#<')
          # use reflection
          value_buff = LogBuffer.new(@@config.data_output_width)
          if @@reflected_objects.any? { |obj| value.equal?(obj) }
            # cyclic reference
            value_buff.no_break_append(@@config.circular_reference_string)
          elsif @@reflected_objects.length > print_options.reflection_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(value_buff)
        else
          buff.append(to_s_string)
        end
      rescue => e
        buff.append("Raised #{e.class.to_s}: '#{e.message}'")
      end
    end
  end

  return buff
end

.to_string_bytes(value, print_options) ⇒ Object

Returns a string representation of the string value which encoding is ASCII_8BIT.

Parameters:

  • value (String)

    the value

  • print_options (PrintOptions)

    the print options



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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/debugtrace.rb', line 291

def self.to_string_bytes(value, print_options)
  bytes_length = value.length
  buff = LogBuffer.new(@@config.data_output_width)

  if bytes_length >= print_options.minimum_output_length
    buff.no_break_append(format(@@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 && multi_lines
      buff.no_break_append('| ')
      buff.no_break_append(chars)
      buff.line_feed
      chars = ''
    end
    if count >= print_options.output_length_limit
      buff.no_break_append(@@config.limit_string)
      break
    end
    buff.no_break_append(format('%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_enumerable(values, print_options) ⇒ Object

Returns a string representation of an Array, Set or Hash.

Parameters:

  • value (Array, Set, Hash)

    the value

  • print_options (PrintOptions)

    the print options



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
452
453
454
455
456
457
458
459
460
461
# File 'lib/debugtrace.rb', line 424

def self.to_string_enumerable(values, print_options)
  open_char = '[' # Array 
  close_char = ']'

  if values.is_a?(Hash)
    # Hash
    open_char = '{'
    close_char = '}'
  elsif values.is_a?(Set)
    # Set
    open_char = 'Set['
    close_char = ']'
  end

  buff = LogBuffer.new(@@config.data_output_width)
  buff.append(get_type_name(values, values.size, print_options))
  buff.no_break_append(open_char)

  body_buff = to_string_enumerable_body(values, print_options)

  multi_lines = body_buff.multi_lines? || buff.length + body_buff.length > @@config.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_enumerable_body(values, print_options) ⇒ Object

Returns a string representation of the Array, Set or Hash value.

Parameters:

  • value (Array, Set, Hash)

    the value

  • print_options (PrintOptions)

    the print options



467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# File 'lib/debugtrace.rb', line 467

def self.to_string_enumerable_body(values, print_options)
  buff = LogBuffer.new(@@config.data_output_width)

  multi_lines = false
  index = 0

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

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

    element_buff = if values.is_a?(Hash)
        # Hash
        to_string_key_value(element[0], element[1], print_options)
      else
        # Array
        to_string('', element, print_options)
      end

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

    multi_lines = element_buff.multi_lines?
    index += 1
  end

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

  return buff
end

.to_string_key_value(key, value, print_options) ⇒ Object

Returns a string representation the key and the value.

Parameters:

  • key (Object)

    the key

  • value (Object)

    the value

  • print_options (PrintOptions)

    the print options



506
507
508
509
510
511
512
# File 'lib/debugtrace.rb', line 506

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

.to_string_reflection(value, print_options) ⇒ Object

Returns a string representation of the value using reflection.

Parameters:

  • value (Object)

    the value

  • print_options (PrintOptions)

    the print options



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/debugtrace.rb', line 349

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

  buff.append(get_type_name(value, -1, print_options))

  body_buff = to_string_reflection_body(value, print_options)

  multi_lines = body_buff.multi_lines? || buff.length + body_buff.length > @@config.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

Returns a string representation of the value using reflection.

Parameters:

  • value (Object)

    the value

  • print_options (PrintOptions)

    the print options



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
411
412
413
414
415
416
417
418
# File 'lib/debugtrace.rb', line 379

def self.to_string_reflection_body(value, print_options)
  buff = LogBuffer.new(@@config.data_output_width)
  multi_lines = false
  index = 0

  variables = value.instance_variables
  variables.each do |variable|
    buff.no_break_append(', ') if index > 0

    var_value = value.instance_variable_get(variable)
    member_buff = LogBuffer.new(@@config.data_output_width)
    member_buff.append(variable).no_break_append(@@config.key_value_separator)
    member_buff.append_buffer(to_string('', var_value, print_options))
    buff.line_feed if index > 0 && (multi_lines || member_buff.multi_lines?)
    buff.append_buffer(member_buff)

    multi_lines = member_buff.multi_lines?
    index += 1
  end

  if value.class.superclass == Struct
    members = value.members
    hash = value.to_h
    members.each do |member|
      buff.no_break_append(', ') if index > 0

      var_value = hash[member]
      member_buff = LogBuffer.new(@@config.data_output_width)
      member_buff.append(member).no_break_append(@@config.key_value_separator)
      member_buff.append_buffer(to_string('', var_value, print_options))
      buff.line_feed if index > 0 && (multi_lines || member_buff.multi_lines?)
      buff.append_buffer(member_buff)

      multi_lines = member_buff.multi_lines?
      index += 1
    end
  end

  return buff
end

.to_string_str(value, print_options) ⇒ Object

Returns a string representation of the string value

Parameters:

  • value (String)

    the value

  • print_options (PrintOptions)

    the print options



228
229
230
231
232
233
234
235
236
237
238
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
# File 'lib/debugtrace.rb', line 228

def self.to_string_str(value, print_options)
  double_quote = false
  single_quote_buff = LogBuffer.new(@@config.data_output_width)
  double_quote_buff = LogBuffer.new(@@config.data_output_width)

  if value.length >= print_options.minimum_output_length
    single_quote_buff.no_break_append(format(@@config.length_format, value.length))
    double_quote_buff.no_break_append(format(@@config.length_format, value.length))
  end

  single_quote_buff.no_break_append("'")
  double_quote_buff.no_break_append('"')

  count = 1
  value.each_char do |char|
    if count > print_options.output_length_limit
      single_quote_buff.no_break_append(@@config.limit_string)
      double_quote_buff.no_break_append(@@config.limit_string)
      break
    end
    case char
    when "'"
      double_quote = true
      double_quote_buff.no_break_append(char)
    when '"'
      single_quote_buff.no_break_append(char)
      double_quote_buff.no_break_append("\\\"")
    when "\\"
      double_quote = true
      double_quote_buff.no_break_append("\\\\")
    when "\n"
      double_quote = true
      double_quote_buff.no_break_append("\\n")
    when "\r"
      double_quote = true
      double_quote_buff.no_break_append("\\r")
    when "\t"
      double_quote = true
      double_quote_buff.no_break_append("\\t")
    else
      char_ord = char.ord
      if char_ord >= 0x00 && char_ord <= 0x1F || char_ord == 0x7F
        double_quote = true
        num_str = format('%02X', char_ord)
        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
    end
    count += 1
  end

  double_quote_buff.no_break_append('"')
  single_quote_buff.no_break_append("'")

  return double_quote ? double_quote_buff : single_quote_buff
end