Simple and Ideal Logging in Sinatra

2019-03-31 00:35发布

问题:

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

回答1:

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).



回答2:

See my suggestion here: Logging in Sinatra?

However, it sounds from your question like the problem is that App is a module.

your Sinatra main class should be something like this:

class App < Sinatra::Base

as opposed to

module App < Sinatra::Base

Make sure you've defined it as a class and that error should go away.