Module: DebugTrace

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

Overview

© 2025 Masato Kokubo frozen_string_literal: true

Defined Under Namespace

Classes: PrintOptions

Constant Summary collapse

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



18
19
20
# File 'lib/debugtrace.rb', line 18

def self.config
  return @@config
end

.current_stateObject



89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/debugtrace.rb', line 89

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



506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
# File 'lib/debugtrace.rb', line 506

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



102
103
104
105
106
# File 'lib/debugtrace.rb', line 102

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



414
415
416
417
418
419
420
421
422
423
# File 'lib/debugtrace.rb', line 414

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

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

  return type_name
end

.has_to_s_method?(value) ⇒ Boolean

Returns:

  • (Boolean)


425
426
427
428
429
430
431
432
# File 'lib/debugtrace.rb', line 425

def self.has_to_s_method?(value)
  begin
    value.public_method('to_s')
  rescue
    return false
  end
  return true
end

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



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

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



567
568
569
570
571
572
573
574
575
576
577
# File 'lib/debugtrace.rb', line 567

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
  @@thread_mutex.synchronize do
    state = current_state
  end

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

.leave(return_value = nil) ⇒ Object



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

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


455
456
457
458
459
460
461
462
463
464
465
466
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
500
501
502
503
504
# File 'lib/debugtrace.rb', line 455

def self.print(name, value = @@DO_NOT_OUTPUT,
    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(
        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


436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/debugtrace.rb', line 436

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



108
109
110
111
112
113
114
115
116
117
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
# File 'lib/debugtrace.rb', line 108

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 = 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
    # 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)
  end

  return buff
end

.to_string_bytes(value, print_options) ⇒ Object



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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/debugtrace.rb', line 222

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



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
368
369
370
# File 'lib/debugtrace.rb', line 333

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



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

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



406
407
408
409
410
411
412
# File 'lib/debugtrace.rb', line 406

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



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

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



309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/debugtrace.rb', line 309

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



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

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(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 "'"
      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")
    else
      char_ord = char.ord
      if char_ord >= 0x00 && char_ord <= 0x1F || char_ord == 0x7F
        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
    end
    count += 1
  end

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

  return has_single_quote && !has_double_quote ? double_quote_buff : single_quote_buff
end