How to add comments to requests with ActiveRecord?
I want to add a comment to every request send by active record in order to fo开发者_运维技巧und source in mysql slow query. How can I modify the request before ActiveRecord sends it?
For example i want to have this in my central mysql slow query log.
SELECT * FROM articles
-- File: refresh-article.rb
ActiveRecord already logs db requests with timing information to your app log.
I solve the problem with monkey patch
ActiveRecord::ConnectionAdapters::Mysql2Adapter.class_eval do
def execute_with_log(sql, name=nil)
sql = "-- Script: #{$0}\n#{sql}"
execute_without_log(sql, name)
end
alias_method_chain :execute, :log
end
In your rails app, you can see your queries with timing in log/(production|development).log
.
However if you want anything more than that, I suggest checking out NewRelic in development mode. It is free, and it shows your the source of where that query was executed(which looks like what you want). It really is one of the best logging/performance analyzer out there.
I found a solution by monkey patch MySQL2::execute
ActiveRecord 6 allows queries to be annotated
User.annotate("selecting user names").select(:name)
# SELECT "users"."name" FROM "users" /* selecting user names */
User.annotate("selecting", "user", "names").select(:name)
# SELECT "users"."name" FROM "users" /* selecting */ /* user */ /* names */
https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-annotate
You could combine this with the caller_locations
kernel method:
User.annotate("#{caller_locations(1,1).first}").select(:name)
https://www.rubydoc.info/stdlib/core/2.0.0/Kernel:caller_locations
精彩评论