Easy logging with Sinatra

2009 March 28
tags: ,
by Nick

UPDATE: This post is no longer relevant and I haven’t had time to update it, check google for a more current post on this topic.

config.ru

log = File.new("sinatra.log", "a+")
$stdout.reopen(log)
$stderr.reopen(log)

app.rb

configure do
  LOGGER = Logger.new("sinatra.log")
end
 
helpers do
  def logger
    LOGGER
  end
end

Now whenever you need to debug something in your application or can’t figure out why something isn’t working just send the area in question to your log file.

get '/'
  logger.info "Index accessed"
end
 
4 Responses leave one →
  1. May 29, 2009

    Couldn’t get this to work. Could you expand on your example?

  2. May 29, 2009

    Appears that perhaps it needs a require ‘logger’ at the top. Is it really using Rack’s Rack::CommonLogger though? Your code appears just to be using Logger.

  3. Nick permalink*
    May 29, 2009

    “Logger” is part of Rack so when you require Rack you get logger too so no you don’t need a “require ‘logger’” at the top.

    What isn’t working for you? Are you getting an error or is it just not writing to the log?

  4. November 14, 2009

    Very helpful, I had to require ‘logger’

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS