我们有一套应用程序的MySQL慢查询日志,大部分是Ruby语言,一些使用Rails ActiveRecord,另一些使用Sequel。
我们希望能够很容易地跟踪一个特定的(MySQL)慢查询返回到生成它的代码。有没有可以在这些工具中启用的功能,或者可以应用于它们的补丁,将插入到SQL注释中的插装添加到__FILE__和__FUNCTION__标识符中?
发布于 2012-10-17 09:13:24
有趣的问题,这是我将如何处理它。
我会使用config.active_record.auto_explain_threshold_in_seconds to automatically explain slow queries,就像你在做的那样。
然后,我将覆盖ActiveRecord::Explain中的logging_query_plan方法以将任何相关数据添加到您的日志中。下面是一个添加当前堆栈跟踪的示例:
# /config/initializers/add_additional_instumentation_to_explain.rb
module ActiveRecord
module Explain
def logging_query_plan # :nodoc:
return yield unless logger
threshold = auto_explain_threshold_in_seconds
current = Thread.current
if threshold && current[:available_queries_for_explain].nil?
begin
queries = current[:available_queries_for_explain] = []
start = Time.now
result = yield
if Time.now - start > threshold
# START ADDING ADDITIONAL INFORMATION
begin
puts 'ADDING ADDITIONAL INFORMATION...'
raise 'foo'
rescue
puts 'DISPLAYING THE CURRENT STACKTRACE FOR THE FOLLOWING EXPLAIN'
puts $@
end
logger.warn(exec_explain(queries))
end
result
ensure
current[:available_queries_for_explain] = nil
end
else
yield
end
end
end
end我更喜欢不依赖于rails整个修改方法的方法,但这是唯一能让它可靠地工作的方法。
不管它有什么价值,这将很容易成为一个gem,每个rails版本都有一个新的gem,并且只需要在每个应用程序中包含与您的版本相关的gem,因为听起来您可能支持rails的多个版本。这将有助于将上述方法的一些脆弱性降至最低。无论如何,希望这能帮到你--祝你好运!
发布于 2012-10-11 22:30:25
我强烈推荐rack-mini-profiler来帮助你快速了解你的Rails (或其他基于机架的)应用程序是如何花费时间的。它特别擅长显示哪些Ruby代码生成了哪些SQL语句。访问下面的所有三个链接,学习如何很好地使用它。祝好运。
http://miniprofiler.com/
http://railscasts.com/episodes/368-miniprofiler
http://samsaffron.com/archive/2012/07/12/miniprofiler-ruby-edition
https://stackoverflow.com/questions/12648414
复制相似问题