diff --git a/lib/uber_task.rb b/lib/uber_task.rb index 2c8548f..9844667 100644 --- a/lib/uber_task.rb +++ b/lib/uber_task.rb @@ -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 diff --git a/lib/uber_task/internal.rb b/lib/uber_task/internal.rb index 5c62b48..36c9d77 100644 --- a/lib/uber_task/internal.rb +++ b/lib/uber_task/internal.rb @@ -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 diff --git a/spec/uber_task/internal_spec.rb b/spec/uber_task/internal_spec.rb index 3b0df77..969dae1 100644 --- a/spec/uber_task/internal_spec.rb +++ b/spec/uber_task/internal_spec.rb @@ -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 diff --git a/spec/uber_task/logger_spec.rb b/spec/uber_task/logger_spec.rb new file mode 100644 index 0000000..14f87dc --- /dev/null +++ b/spec/uber_task/logger_spec.rb @@ -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