Class: Profiler::ConsoleProfiler

Inherits:
Object
  • Object
show all
Defined in:
lib/profiler/console_profiler.rb

Constant Summary collapse

CONSOLE_COLLECTOR_CLASSES =
[
  Collectors::DatabaseCollector,
  Collectors::CacheCollector,
  Collectors::HttpCollector,
  Collectors::DumpCollector,
  Collectors::LogCollector,
  Collectors::ExceptionCollector,
  Collectors::EnvCollector,
  Collectors::FlameGraphCollector
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expression:) ⇒ ConsoleProfiler

Returns a new instance of ConsoleProfiler.



34
35
36
# File 'lib/profiler/console_profiler.rb', line 34

def initialize(expression:)
  @expression = expression
end

Class Method Details

.profile(expression:, &block) ⇒ Object



28
29
30
31
32
# File 'lib/profiler/console_profiler.rb', line 28

def self.profile(expression:, &block)
  return block.call unless Profiler.enabled? && Profiler.configuration.track_console

  new(expression: expression).run(&block)
end

Instance Method Details

#run(&block) ⇒ Object



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
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/profiler/console_profiler.rb', line 38

def run(&block)
  profile = Models::Profile.new
  profile.profile_type = "console"
  profile.gem_version = Profiler::VERSION
  profile.path = @expression.length > 200 ? "#{@expression[0, 200]}..." : @expression
  profile.method = "CONSOLE"

  console_collector = Collectors::ConsoleCollector.new(profile, expression: @expression)
  collectors = [console_collector] + CONSOLE_COLLECTOR_CLASSES.map { |klass| klass.new(profile) }
  collectors.each { |c| c.subscribe if c.respond_to?(:subscribe) }

  exception_collector = collectors.find { |c| c.is_a?(Collectors::ExceptionCollector) }

  memory_before = current_memory if Profiler.configuration.track_memory

  console_status = "completed"

  previous_token = Profiler::CurrentContext.token
  Profiler::CurrentContext.token = profile.token
  result = nil
  begin
    result = block.call
    console_collector.set_return_value(result)
    result
  rescue => e
    console_status = "failed"
    exception_collector&.capture(e)
    raise
  ensure
    Profiler::CurrentContext.token = previous_token
    if Profiler.configuration.track_memory
      profile.memory = current_memory - memory_before
    end

    profile.finish(console_status == "completed" ? 200 : 500)

    collectors.each do |collector|
      begin
        collector.collect if collector.respond_to?(:collect)
        profile.(collector)
      rescue => e
        warn "Profiler ConsoleProfiler: Collector #{collector.class} failed: #{e.message}"
      end
    end

    Profiler.storage.save(profile.token, profile)
  end
end