在日志中包含Active Record查询的角色



Rails现在支持多个数据库角色(默认情况下,writing用于主数据库,reading用于副本):

ActiveRecord::Base.connected_to(role: :reading) do
# all code in this block will be connected to the reading role
end

在开发中,默认情况下记录活动记录查询,例如:

> User.last
User Load (0.1ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT ?  [["LIMIT", 1]]

如何在日志记录中包含查询使用的角色?例如:

> ActiveRecord::Base.connnected_to(role: :reading) { User.last }
[role: reading] User Load (0.1ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT ?  [["LIMIT", 1]]

创建一个新文件config/initializers/multidb_logger.rb,代码如下:

ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do
alias_method(:origin_log, :log)
def log(sql, name = 'SQL', binds = [], type_casted_binds = [], statement_name = nil, &block)
sql = "#{sql} /* #{@config[:replica] ? 'REPLICA' : 'MASTER'} DB */"
origin_log(sql, name, binds, type_casted_binds, statement_name, &block)
end
end
ActiveRecord::LogSubscriber.class_eval do
alias_method(:origin_extract_query_source_location, :extract_query_source_location)
def extract_query_source_location(locations)
new_locations = locations.reject { |loc| loc.include? File.basename(__FILE__) }
origin_extract_query_source_location(new_locations)
end
end

现在,在ActiveRecord记录的SQL查询中,您将看到"REPLICA DB"或"MASTER db";在每个查询的末尾。

这个解决方案使用了与@Lam Phan解决方案类似的方法,但它保留了所有标准的日志记录行为:

  • 不记录SCHEMA查询
  • 正确显示触发查询的源文件和行

还请注意,我没有使用ActiveRecord::Base.current_role来获取角色,因为它没有显示可靠的信息(即它打印角色writing,但查询转到副本DB)。

可以使用@config散列中可用的信息进一步定制日志,如hostportdatabase等。

因为所有查询都将在最后一步由类AbstractAdapter的方法日志记录,无论您使用的是哪种数据库适配器:postgresql, mysql,…所以你可以重写这个方法并加上role

# lib/extent_dblog.rb
ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do
alias_method(:origin_log, :log)
def log(sql, name = 'SQL', binds = [], 
type_casted_binds = [], statement_name = nil, &block)
# prepend the current role before the log
name = "[role: #{ActiveRecord::Base.current_role}] #{name}"
origin_log(sql, name, binds, type_casted_binds, statement_name, &block)
end
end
# config/initializers/ext_log.rb
require File.join(Rails.root, "lib", "extent_dblog.rb")

演示
# config/application.rb
...
config.active_record.reading_role = :dev
config.active_record.reading_role = :test
# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
connects_to database: { dev: :development, test: :test }
end
ActiveRecord::Base.connected_to(role: :dev) do
Target.all
end
# [role: dev]  (0.6ms)  SELECT "targets".* FROM "targets" 

相关内容

  • 没有找到相关文章

最新更新