How do I access Sinatra's Logger outside the Request Scope

后端 未结 2 856
悲&欢浪女
悲&欢浪女 2021-02-20 18:12

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

2条回答
  •  悲哀的现实
    2021-02-20 18:52

    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
    

提交回复
热议问题