How to erase SQL queries from ActiveRecord::Base.logger
I'm developing an application using Ruby on Rails.
I would like to erase old queries in the ActiveRecord::Base.logger object every time when I call a new action, essentially where ENV = production.
The goal is not to erase all queries like using config.log_level :info. I need only last queries to build a file with those queries.
Here is some code:
in the lib:
module SqlHunter
class ActiveRecord::ConnectionAdapters::AbstractAdapter
@@queries = [] # without this line it work perfectly
@@logging = false
cattr_accessor :queries, :logging
def log_info_with_trace(sql, name, runtime)
@@queries << sql if @@logg开发者_运维问答ing
end
alias_method_chain :log_info, :trace
end
end
in the controller (report action)
ActiveRecord::ConnectionAdapters::AbstractAdapter::logging = true
.....
sqlfile = File.open("public/advancedStats/#{@dir_name}/advancedStatQuery.sql", 'w')
@queries = ActiveRecord::ConnectionAdapters::AbstractAdapter::queries
for query in @queries do
sqlfile.write("#{query} \n")
end
sqlfile.close
I asked an old related question here
link text
Thanks to Tamás Mezei and Damien MATHIEU for their last answer
Mondher
So you want to filter the SQL queries in production mode or am I missing the point?
If it's about just filtering, prod mode will automatically filter sql queries. If you'd like to filter when developing, edit the config/environments/development.rb file and insert
config.log_level = :info
Essentially, it will filter SQL with all the other stuff that's below info level (debug stuff).
If you want some more sophisticated solution, you can always exend/override the AbstractAdapter class in
RUBY_HOME/lib/gems/1.8/gems/activerecord-nnn/active_record/connection_adapters/abstract_adapter.rb
精彩评论