如何更改Sinatra中的日志级别

我正在使用此代码启用我的Sinatra应用程序中的日志记录:

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

实际记录使用以下方式完成:

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

事实certificate,只记录INFO或更高级别的日志消息,并且不记录DEBUG消息。 我正在寻找一种方法来设置日志级别为DEBUG。

我想可能有更好的方法,但你总是可以做一些事情,比如beforefilter中设置日志级别:

 before do logger.level = 0 end 

您可以使用设置日志级别

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

Sinatra在其默认中间件中为您设置Rack :: Logger,可以使用日志级别对其进行初始化(请参阅http://rack.rubyforge.org/doc/Rack/Logger.html )。 Sinatra使用您的logging设置初始化它,因此您可以在其中放置一个数字(或Logger常量)而不是true

仅供参考,这是来自Sinatra::Base源代码的相关方法,初始化Rack :: Logger中间件( 在此处找到 )

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

这是在Sinatra 1.3.2上,我不知道它是否在早期版本中有所不同

在我的情况下,我能够可靠地记录工作的唯一方法如下:(简化示例)

首先,我按如下方式设置记录器和日志文件夹:

 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 

然后在单独的环境配置中

 configure :test do set :logging, Logger::ERROR end configure :development do set :logging, Logger::DEBUG end configure :production do set :logging, Logger::INFO end 

这是一种享受。