Pat*_*ois 3 logging activerecord ruby-on-rails multi-database
Rails 现在支持多个数据库角色(默认情况下,writing对于主数据库和reading副本数据库角色):
ActiveRecord::Base.connected_to(role: :reading) do
# all code in this block will be connected to the reading role
end
Run Code Online (Sandbox Code Playgroud)
在开发中,默认情况下会记录 Active Record 查询,例如:
> User.last
User Load (0.1ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT ? [["LIMIT", 1]]
Run Code Online (Sandbox Code Playgroud)
如何在日志记录中包含用于查询的角色?例如:
> 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]]
Run Code Online (Sandbox Code Playgroud)
因为所有查询都将在最后一步由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")
Run Code Online (Sandbox Code Playgroud)
演示
# 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"
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
现在,在 ActiveRecord 记录的 SQL 查询中,您将在每个查询的末尾看到“REPLICA DB”或“MASTER DB”。
该解决方案使用与 @Lam Phan 解决方案类似的方法,但它保留了所有标准日志记录行为:
另请注意,我没有用来ActiveRecord::Base.current_role获取角色,因为它没有显示可靠的信息(即它打印角色writing,但查询转到副本数据库)。
可以使用哈希中的可用信息进一步自定义日志@config,例如host、port、database等。
| 归档时间: |
|
| 查看次数: |
1032 次 |
| 最近记录: |