Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/lograge/active_record_log_subscriber.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ def filter_query(event)
end

def valid?(event)
return false unless Lograge::Sql.store_active?
return false if event.payload[:name]&.match?(Lograge::Sql.query_name_denylist)

# Only store SQL events if `event.duration` is greater than the configured +min_duration+
Expand Down
11 changes: 11 additions & 0 deletions lib/lograge/sql.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,17 @@ def setup(config) # rubocop:disable Metrics/AbcSize
Lograge::ActiveRecordLogSubscriber.attach_to(:active_record)
end

# Whether SQL events can be stored right now.
# Only a logged request drains the store, so with RequestStore events are stored only while a request
# is being processed: queries from Sidekiq jobs, Action Cable workers or other background threads
# would otherwise pile up in their thread forever.
# @return [Boolean]
def store_active?
return true unless defined?(RequestStore) && RequestStore.respond_to?(:active?)

RequestStore.active?
end

# Gets the store, preferring RequestStore if the gem is found.
# @return [Hash, Thread] the RequestStore or the current Thread.
def store
Expand Down
26 changes: 26 additions & 0 deletions spec/lograge/active_record_log_subscriber_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@
Lograge::Sql.extract_event = proc {}
Lograge::Sql.store.clear
Lograge::Sql.query_name_denylist = Regexp.union([/\ASCHEMA\z/, /\ASolidCable::/])
RequestStore.begin!
end

after { RequestStore.end! }

context 'with keep_default_active_record_log not set' do
before do
allow(Rails).to receive_message_chain('application.config.lograge_sql.keep_default_active_record_log') { nil }
Expand Down Expand Up @@ -98,6 +101,29 @@
end
end

context 'outside of a request' do
before do
allow(Rails).to receive_message_chain('application.config.lograge_sql.keep_default_active_record_log') { true }
RequestStore.end!
end

it 'does not store the event' do
log_subscriber.sql(event)
expect(Lograge::Sql.store[:lograge_sql_queries]).to be_nil
end
end

context 'within a request' do
before do
allow(Rails).to receive_message_chain('application.config.lograge_sql.keep_default_active_record_log') { true }
end

it 'stores the event' do
log_subscriber.sql(event)
expect(Lograge::Sql.store[:lograge_sql_queries]).not_to be_nil
end
end

context 'with default name denylist' do
before do
allow(Rails).to receive_message_chain('application.config.lograge_sql.keep_default_active_record_log') { true }
Expand Down