Skip to content

Commit 44758f8

Browse files
committed
Active Record logging includes the tenant name
1 parent 8211e03 commit 44758f8

File tree

4 files changed

+39
-0
lines changed

4 files changed

+39
-0
lines changed

lib/active_record/tenanted/database_configurations.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,22 @@ def database_path_for(tenant_name)
1919
end
2020

2121
class TenantConfig < RootConfig
22+
def tenant
23+
configuration_hash.fetch(:tenant)
24+
end
25+
26+
def new_connection
27+
conn = super
28+
log_addition = " [tenant=#{tenant}]"
29+
conn.instance_eval <<~CODE, __FILE__, __LINE__ + 1
30+
def log(sql, name = "SQL", binds = [], type_casted_binds = [], async: false, &block)
31+
name ||= ""
32+
name += "#{log_addition}"
33+
super(sql, name, binds, type_casted_binds, async: async, &block)
34+
end
35+
CODE
36+
conn
37+
end
2238
end
2339
end
2440
end

lib/active_record/tenanted/tenant.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ def create_tenanted_pool # :nodoc:
5757
base_config = ActiveRecord::Base.configurations.resolve(tenanted_config_name.to_sym)
5858
tenant_name = "#{tenanted_config_name}_#{tenant}"
5959
config_hash = base_config.configuration_hash.dup.tap do |hash|
60+
hash[:tenant] = tenant
6061
hash[:database] = base_config.database_path_for(tenant)
6162
end
6263
config = Tenanted::DatabaseConfigurations::TenantConfig.new(base_config.env_name, tenant_name, config_hash)

test/test_helper.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,15 @@ def with_each_scenario(&block)
9999
end
100100
end
101101

102+
def capture_log
103+
StringIO.new.tap do |log|
104+
logger_was, ActiveRecord::Base.logger = ActiveRecord::Base.logger, ActiveSupport::Logger.new(log)
105+
yield
106+
ensure
107+
ActiveRecord::Base.logger = logger_was
108+
end
109+
end
110+
102111
private def create_fake_record
103112
# emulate models like ActiveStorage::Record that inherit directly from AR::Base
104113
Object.const_set(:FakeRecord, Class.new(ActiveRecord::Base))

test/unit/tenant_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,17 @@
6969
end
7070
end
7171
end
72+
73+
describe "logging" do
74+
with_each_scenario do
75+
test "database logs should emit the tenant name" do
76+
log = capture_log do
77+
TenantedApplicationRecord.while_tenanted("foo") do
78+
User.count
79+
end
80+
end
81+
assert_includes(log.string, "[tenant=foo]")
82+
end
83+
end
84+
end
7285
end

0 commit comments

Comments
 (0)