Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple and Ideal Logging in Sinatra

I went through few blogs and sites which gave me some information about how to log in sinatra but didnt work for my app and also i went through a gem called sinatra-logger didnt tried it, wanted to know ideal and simple way to "log" in sinatra. Like we do logger.info for rails.

The code which i tried and didnt work is from the following site link and also some of SO links were too pointing to the same approach used in the link above.

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

helpers do
 def logger
  LOGGER
 end
end

i have written this in app.rb of my app, it fails saying undefined method `configure' for App:Module

Any pointers or guide would be helpful. Thanks.

Edits Right Now am using file write to log my errors and messages:

File.open('log.txt', 'a') do |f|
 f.write "#{status}-#{CONFIG.api_url}-#{data.inspect}-tweet}"
end
like image 516
abhijit Avatar asked Nov 29 '22 15:11

abhijit


1 Answers

If you are using Sinatra 1.3 you should be able to log just like in rails with logger.info

The following is copied from the Sinatra Readme:


Logging

In the request scope, the logger helper exposes a Logger instance:

get '/' do
  logger.info "loading data"
  # ...
end

This logger will automatically take your Rack handler’s logging settings into account. If logging is disabled, this method will return a dummy object, so you do not have to worry in your routes and filters about it.

Note that logging is only enabled for Sinatra::Application by default, so if you inherit from Sinatra::Base, you probably want to enable it yourself:

 class MyApp < Sinatra::Base
   configure :production, :development do
     enable :logging
   end
 end

To avoid any logging middleware to be set up, set the logging setting to nil. However, keep in mind that logger will in that case return nil. A common use case is when you want to set your own logger. Sinatra will use whatever it will find in env['rack.logger'].


Rack::CommonLogger generates the log messages internally (I think).

like image 71
Sean Lerner Avatar answered Feb 15 '23 07:02

Sean Lerner