How to change the log level in Sinatra

梦想与她 提交于 2019-12-22 05:28:25

问题


I am using this code to enable logging in my Sinatra app:

log_file = File.new('my_log_file.log', "a") 
$stdout.reopen(log_file)
$stderr.reopen(log_file)    
$stdout.sync=true
$stderr.sync=true

The actual logging is done using:

logger.debug("Starting call. Params = #{params.inspect}")

It turns out that only INFO or higher level log messages are logged and DEBUG messages are not logged. I am looking for a way to set up the log level to DEBUG.


回答1:


I guess there might be a better way, but you can always do something like setting the log level in a before filter:

before do
  logger.level = 0
end



回答2:


You can set the log level using

configure :development do
  set :logging, Logger::DEBUG
end

Sinatra sets you up with Rack::Logger in its default middleware, which can be initialized with a log level (see http://rack.rubyforge.org/doc/Rack/Logger.html). Sinatra initializes it with your logging setting, so you can put a number (or Logger constant) there instead of just true.

FYI, here is the relevant method from the Sinatra::Base source code that initializes the Rack::Logger middleware (found here)

def setup_custom_logger(builder)
  if logging.respond_to? :to_int
    builder.use Rack::Logger, logging
  else
    builder.use Rack::Logger
  end
end

This is on Sinatra 1.3.2, I don't know if it was different in earlier versions




回答3:


In my situation the only way I could get logging to work reliably was as follows: (simplified example)

Firstly I set up the logger and log folder as follows:

require 'logger'

configure do
  log_dir = "#{root}/log"
  Dir.mkdir(log_dir) unless Dir.exists?(log_dir)
  file = File.new("#{log_dir}/#{environment}.log", 'a+')
  file.sync = true
  use Rack::CommonLogger, file
end

Then in separate environment config

configure :test do
  set :logging, Logger::ERROR
end

configure :development do
  set :logging, Logger::DEBUG
end

configure :production do
  set :logging, Logger::INFO
end

This works a treat.



来源:https://stackoverflow.com/questions/8429326/how-to-change-the-log-level-in-sinatra

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!