How to change the log level in Sinatra

断了今生、忘了曾经 提交于 2019-12-05 06:38:06

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

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

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.

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