Search code examples
loggingsinatra

How can I log and debug in an older Sinatra API application?


I have this old, simple Sinatra API. It's version 1.4.8. It's very simple, and it's going to be rewritten. In the short term I need to add some debug statements to it in order to fix something. I'm find with just sending them to STDOUT to watch them in realtime on the screen.

I saw that a logger was included in version 1.3 but I can't seem to find a good tutorial page for how to implement it. I don't need a complicated logging class. The most I would ever want to do is just log to a file. Is there a simple way of doing either of these without a significant time investment?


Solution

  • I found this page which outlines the process very nicely.

    This code block contains my changes:

    ::Logger.class_eval { alias :write :'<<' }
    access_log = ::File.join(::File.dirname(::File.expand_path(__FILE__)),'log','access.log')
    $access_logger = ::Logger.new(access_log)
    $error_logger = ::File.new(::File.join(::File.dirname(::File.expand_path(__FILE__)),'log','error.log'),"a+")
    $error_logger.sync = true
    
    configure :development do
      $access_logger.level = Logger::DEBUG
      use ::Rack::CommonLogger, $access_logger
    end
    
    configure :production do
      $access_logger.level = Logger::WARN
      use ::Rack::CommonLogger, $access_logger
    end  
    

    I just changed the logging level for dev and production. I also made the loggers into variables that I can access from other parts of my code.

    So for my main API module, I can output the contents of variables or anything else with this:

    $access_logger.debug "subscription_id is #{subscription_id}."
    

    Works great!