Skip to content

Commit

Permalink
Add configurable logger usage (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
zzaakiirr authored Jul 8, 2024
1 parent a7b09b9 commit d92f0da
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 6 deletions.
13 changes: 13 additions & 0 deletions lib/uber_task.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@
require 'uber_task/task_context'

module UberTask
class << self
attr_writer :logger

def logger
@logger ||=
if defined?(Rails.logger)
Rails.logger
else
Logger.new($stdout, progname: name)
end
end
end

def self.current
Thread.current[:__uber_task_stack__] ||= []
Thread.current[:__uber_task_stack__].last
Expand Down
3 changes: 1 addition & 2 deletions lib/uber_task/internal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ module Internal
def self.trace
return unless Thread.current[:__uber_task_trace__]

message = yield
puts message
UberTask.logger.debug yield
end
end
end
8 changes: 4 additions & 4 deletions spec/uber_task/internal_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@
UberTask.enable_tracing
end

it 'sends the trace message to puts' do
expect do
described_class.trace { 'some message' }
end.to output("some message\n").to_stdout
it 'logs the trace message via logger\'s debug level' do
expect(UberTask.logger).to receive(:debug).with('some message')

described_class.trace { 'some message' }
end
end
end
Expand Down
37 changes: 37 additions & 0 deletions spec/uber_task/logger_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# frozen_string_literal: true

describe UberTask do
before do
described_class.instance_variable_set(:@logger, nil)
end

describe '.logger' do
it 'memoizes variable' do
initialized_logger = described_class.logger

expect(described_class.logger.object_id).to eq(
initialized_logger.object_id,
)
end

context 'when Rails logger is not defined' do
it 'uses stdout logger by default' do
expect do
described_class.logger.info('some message')
end.to output(/some message/).to_stdout
end
end
end

describe '.logger=' do
it 'changes logger' do
old_logger = described_class.logger
new_logger = Logger.new($stderr)

described_class.logger = new_logger

expect(described_class.logger).to eq(new_logger)
expect(described_class.logger).not_to eq(old_logger)
end
end
end

0 comments on commit d92f0da

Please sign in to comment.