discourse / prometheus_exporter

A framework for collecting and aggregating prometheus metrics
MIT License
532 stars 154 forks source link

uninitialized constant ActiveRecord (NameError) when using Activerecord Connection Pool Metrics #156

Open h0jeZvgoxFepBQ2C opened 3 years ago

h0jeZvgoxFepBQ2C commented 3 years ago

I did like it's written in the documentation, but I get following error:

/usr/local/bundle/gems/prometheus_exporter-0.7.0/lib/prometheus_exporter/instrumentation/active_record.rb:11:in `start': uninitialized constant ActiveRecord (NameError)
  from /company/config/puma/production.rb:21:in `_load_from'
  from /usr/local/bundle/gems/puma-4.3.7/lib/puma/dsl.rb:46:in `instance_eval'
  from /usr/local/bundle/gems/puma-4.3.7/lib/puma/dsl.rb:46:in `_load_from'
  from /usr/local/bundle/gems/puma-4.3.7/lib/puma/configuration.rb:195:in `block in load'
  from /usr/local/bundle/gems/puma-4.3.7/lib/puma/configuration.rb:195:in `each'
  from /usr/local/bundle/gems/puma-4.3.7/lib/puma/configuration.rb:195:in `load'
  from /usr/local/bundle/gems/puma-4.3.7/lib/puma/launcher.rb:58:in `initialize'
  from /usr/local/bundle/gems/puma-4.3.7/lib/puma/cli.rb:71:in `new'
  from /usr/local/bundle/gems/puma-4.3.7/lib/puma/cli.rb:71:in `initialize'
  from /usr/local/bundle/gems/puma-4.3.7/bin/puma:8:in `new'
  from /usr/local/bundle/gems/puma-4.3.7/bin/puma:8:in `<top (required)>'
  from /usr/local/bundle/bin/puma:23:in `load'
  from /usr/local/bundle/bin/puma:23:in `<main>'

here is my simple puma config:

#!/usr/bin/env puma

bind 'tcp://0.0.0.0:3000'

threads 2, 2

environment "production"

require 'prometheus_exporter/instrumentation'
PrometheusExporter::Instrumentation::ActiveRecord.start(
  custom_labels: { type: "puma_single_mode" }, #optional params
  config_labels: [:database, :host] #optional params
)
modulitos commented 2 years ago

I encountered this same issue, and it might have to do with puma running in "single" mode, where we are loading the prometheus_exporter code before AR has been loaded.

I worked around it by adding PrometheusExporter::Instrumentation::ActiveRecord.start to my initializer. So my prometheus_exporter initializer looks like this:

unless Rails.env.test?
  require 'prometheus_exporter/middleware'
  require 'prometheus_exporter/instrumentation'

  Rails.application.middleware.unshift(PrometheusExporter::Middleware)

  PrometheusExporter::Instrumentation::ActiveRecord.start
end