Neil
Neil

Reputation: 5178

Rails Logs: Only show Create, Update, and Destroy SQL statements in Logs and nothing else

I only want to see CREATE/UPDATE/DESTROY-related sql statements in the logs. I do not want any READ-related statements, caches, or any other information displayed in the logs because it is making it tough to sift through.

Currently within app/config/environments/production.rb I have the following configuration set which shows way too much in the logs:

config.log_level = :debug

The default config for production shows too little information. It ignores all the sql statements I want to see:

# shows too little information
config.log_level = :info

Is there a configuration setting in rails to have the logs output only the information I want to see? If not: how might I do this?

Upvotes: 4

Views: 1095

Answers (1)

spickermann
spickermann

Reputation: 106782

You can disable logging of ActiveRecord database queries by setting the log_level to :info.

Then use Rails' ActiveSupport::Instrumentation and subscribe to the sql.active_record event.

Just add the following code into an initializer:

# in `config/initializers/query_logger.rb`
class QueryLogger
  def call(name, started, finished, unique_id, payload)
    query = payload[:sql]

    Rails.logger.info("SQL Query: #{query}") unless query.start_with?('SELECT')
  end
end

ActiveSupport::Notifications.subscribe('sql.active_record', QueryLogger.new)

Upvotes: 7

Related Questions