It seems that Sinatra\'s logger is only available inside request handlers (See https://github.com/sinatra/sinatra#logging), but what if I want to use a logger in other places, f
The accepted answer didn't quite work for me, so I came up with the following:
class AppLogger
extend SingleForwardable
def_delegators :logger, :info, :error, :warn, :level
class << self
def logger
return @_logger if @_logger
@_logger = Logger.new STDOUT
@_logger.level = Logger::INFO
end
def suppress_logging
logger.level = Logger::FATAL
end
end
end
suppress_logging
is useful for keeping specs quiet.
In the app init:
set :logging, AppLogger.logger
From a request:
logger.info "Can't touch this."
From a class that does not have access to the logger
:
AppLogger.info "You've got mail."
And, RSpec mock:
let( :logger ){ double 'logger' }
before do
allow( AppLogger ).to receive( :logger ).and_return logger
allow( logger ).to receive :error
end
specify 'logs error' do
post '/raise/error'
expect( logger ).to have_received( :error ).with 'An error has occured.'
end