Module: DebugTrace

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

Overview

© 2025 Masato Kokubo

Defined Under Namespace

Classes: PrintOptions

Constant Summary collapse

VERSION =
'0.3.0'
@@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 =

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



21
22
23
# File 'lib/debugtrace.rb', line 21

def self.config
  return @@config
end

.current_stateState

Returns the current state.

Returns:

  • (State)

    the current state



110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/debugtrace.rb', line 110

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.



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

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

    state = current_state

    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_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(
      format(@@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) ⇒ 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



128
129
130
131
132
# File 'lib/debugtrace.rb', line 128

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 = -1)) ⇒ Object

Returns the type name.

Parameters:

  • value (Object)

    the value

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

    a customizable set of options

Options Hash (size):

  • the (Object)

    size of Array, Set or Hash



473
474
475
476
477
478
479
480
481
482
# File 'lib/debugtrace.rb', line 473

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

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

  return type_name
end

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

Initialize this class

Parameters:

  • [String] (Hash)

    a customizable set of options



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

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 '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?

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

.last_print_stringObject

Returns the last print string.



637
638
639
640
641
642
643
644
645
646
647
# File 'lib/debugtrace.rb', line 637

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



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

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

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

    @@last_log_buff = LogBuffer.new(@@config.maximum_data_output_width)
    @@last_log_buff.no_break_append(
      format(@@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)
    return return_value
  end
end

Prints the message or the value.

Parameters:

  • name (String)

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

  • 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

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

    a customizable set of options

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

    a customizable set of options

  • string_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 (collection_limit:):

  • Output (Integer)

    limit of collection elements (overrides debugtarace.yml value)

Options Hash (bytes_limit:):

  • the (Integer)

    limit value of elements for bytes and bytearray to output (overrides debugtarace.yml value)

Options Hash (string_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)



517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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
# File 'lib/debugtrace.rb', line 517

def self.print(name, value = @@DO_NOT_OUTPUT,
    reflection: false,
    minimum_output_size: -1, minimum_output_length: -1,
    collection_limit: -1, bytes_limit: -1,
    string_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.maximum_data_output_width)
      @@last_log_buff.no_break_append(name)
    else
      # with value
      print_options = PrintOptions.new(
        reflection,
        minimum_output_size, minimum_output_length,
        collection_limit, bytes_limit,
        string_limit, reflection_limit
      )
      @@last_log_buff = to_string(name, value, print_options)
    end

    # append print suffix
    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(
      format(@@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

Called at the start of the print method.



487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
# File 'lib/debugtrace.rb', line 487

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

  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



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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/debugtrace.rb', line 139

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
    buff.no_break_append(separator).append('nil')
  when FalseClass, TrueClass, Integer, Float
    buff.no_break_append(separator).append(value.to_s)
  when Symbol
    buff.no_break_append(separator).append(':').no_break_append(value.name)
  when Class
    buff.no_break_append(separator).append(value.name).no_break_append(' class')
  when Module
    buff.no_break_append(separator).append(value.name).no_break_append(' module')
  when String
    value_buff = value.encoding == Encoding::ASCII_8BIT ?
        to_string_bytes(value, print_options) : to_string_str(value, print_options)
    buff.append_buffer(separator, value_buff)
  when DateTime
    buff.no_break_append(separator).append(value.strftime('%Y-%m-%d %H:%M-%S.%L%:z'))
  when Date
    buff.no_break_append(separator).append(value.strftime('%Y-%m-%d'))
  when Time
    buff.no_break_append(separator).append(value.strftime('%H:%M-%S.%L%:z'))
  when Array, Set, Hash
    value_buff = to_string_enumerable(value, print_options)
    buff.append_buffer(separator, value_buff)
  else
    if print_options.reflection
      # use reflection
      value_buff = LogBuffer.new(@@config.maximum_data_output_width)
      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_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)
    else
      buff.no_break_append(separator).append(value.to_s)
    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



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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/debugtrace.rb', line 263

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

  if bytes_length >= @@config.minimum_output_length
    buff.no_break_append(format(@@config.size_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.bytes_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



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

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

  if values.is_a?(Hash)
    # Array
    open_char = '{'
    close_char = '}'
  elsif values.is_a?(Set)
    # Sete
    open_char = 'Set['
    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_enumerable_body(values, print_options)

  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_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



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
452
453
454
# File 'lib/debugtrace.rb', line 422

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

  multi_lines = false
  index = 0

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

    if index >= print_options.collection_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



461
462
463
464
465
466
467
# File 'lib/debugtrace.rb', line 461

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)
  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



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/debugtrace.rb', line 321

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

Returns a string representation of the value using reflection.

Parameters:

  • value (Object)

    the value

  • print_options (PrintOptions)

    the print options



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 351

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

  variables = value.instance_variables

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

    var_value = value.instance_variable_get(variable)
    member_buff = LogBuffer.new(@@config.maximum_data_output_width)
    member_buff.append(variable)
    member_buff.append_buffer(@@config.key_value_separator, 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

  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



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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/debugtrace.rb', line 200

def self.to_string_str(value, print_options)
  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(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.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 "'"
      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