Search code examples
rubyloggingsinatrarack

Logging in Sinatra?


I'm having trouble figuring out how to log messages with Sinatra. I'm not looking to log requests, but rather custom messages at certain points in my app. For example, when fetching a URL I would like to log "Fetching #{url}".

Here's what I'd like:

  • The ability to specify log levels (ex: logger.info("Fetching #{url}"))
  • In development and testing environments, the messages would be written to the console.
  • In production, only write out messages matching the current log level.

I'm guessing this can easily be done in config.ru, but I'm not 100% sure which setting I want to enable, and if I have to manually create a Logger object myself (and furthermore, which class of Logger to use: Logger, Rack::Logger, or Rack::CommonLogger).

(I know there are similar questions on StackOverflow, but none seem to directly answer my question. If you can point me to an existing question, I will mark this one as a duplicate).


Solution

  • Sinatra 1.3 will ship with such a logger object, exactly usable as above. You can use edge Sinatra as described in "The Bleeding Edge". Won't be that long until we'll release 1.3, I guess.

    To use it with Sinatra 1.2, do something like this:

    require 'sinatra'
    use Rack::Logger
    
    helpers do
      def logger
        request.logger
      end
    end