Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor ReplayLogger to extend Logger #492

Merged
merged 2 commits into from
Feb 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 8 additions & 8 deletions lib/dotenv/replay_logger.rb
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
module Dotenv
# A logger that can be used before the apps real logger is initialized.
class ReplayLogger
class ReplayLogger < Logger
def initialize
super(nil) # Doesn't matter what this is, it won't be used.
@logs = []
end

def method_missing(name, *args, &block)
@logs.push([name, args, block])
end

def respond_to_missing?(name, include_private = false)
(include_private ? Logger.instance_methods : Logger.public_instance_methods).include?(name) || super
# Override the add method to store logs so we can replay them to a real logger later.
def add(*args, &block)
@logs.push([args, block])
end

# Replay the store logs to a real logger.
def replay(logger)
@logs.each { |name, args, block| logger.send(name, *args, &block) }
@logs.each { |args, block| logger.add(*args, &block) }
@logs.clear
end
end
end
16 changes: 15 additions & 1 deletion spec/dotenv/rails_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
require "dotenv/rails"

describe Dotenv::Rails do
let(:log_output) { StringIO.new }
let(:application) do
log_output = self.log_output
Class.new(Rails::Application) do
config.load_defaults Rails::VERSION::STRING.to_f
config.eager_load = false
config.logger = ActiveSupport::Logger.new(StringIO.new)
config.logger = ActiveSupport::Logger.new(log_output)
config.root = fixture_path

# Remove method fails since app is reloaded for each test
Expand Down Expand Up @@ -197,4 +199,16 @@
application.initialize!
end
end

describe "logger" do
it "replays to Rails.logger" do
expect(Dotenv::Rails.logger).to be_a(Dotenv::ReplayLogger)
Dotenv::Rails.logger.debug("test")

application.initialize!

expect(Dotenv::Rails.logger).not_to be_a(Dotenv::ReplayLogger)
expect(log_output.string).to include("test")
end
end
end