【问题标题】:Sinatra doesn't show exceptions in log fileSinatra 不在日志文件中显示异常
【发布时间】:2013-05-25 08:43:14
【问题描述】:

我从 Rails 转到 sinatra,但在使用日志记录时遇到了一些问题。我有一个 Sinatra 应用程序,它的日志记录是这样的:

  configure do
    Logger.class_eval { alias :write :'<<' }
    logger = Logger.new("log/#{settings.environment}.log")
    use Rack::CommonLogger, logger
  end

所有请求都被正确记录,我看到了类似的东西

127.0.0.1 - - [25/May/2013 10:34:21] "GET / HTTP/1.1" 200 30 0.0021
127.0.0.1 - - [25/May/2013 10:34:22] "GET /favicon.ico HTTP/1.1" 404 18 0.0041

在日志文件中。但我也想将应用程序错误记录到日志文件中。当我使用RACK_ENV=production rackup config.ru 在生产环境中启动我的应用程序并发生错误时,它只记录 500 http 状态,而不是错误本身。错误显示在控制台内。这适用于开发,但不适用于生产。错误应该出现在日志文件中以供以后调试。

这是我的config.ru

require 'rubygems'
require 'bundler'
Bundler.require(:default, ENV['RACK_ENV'].to_sym)
disable :run
Encoding.default_external = Encoding::UTF_8

use Rack::ShowExceptions
use Rack::Session::Pool

require File.expand_path '../app.rb', __FILE__
run App

这是我的app.rb

class App < Sinatra::Base
  configure do
    set :public_folder, Proc.new { File.join(root, "public") }
    Logger.class_eval { alias :write :'<<' }
    logger = Logger.new("log/#{settings.environment}.log")
    use Rack::CommonLogger, logger
  end

  get '/' do
    raise "ERROR"
    erb :home, layout: :layout
  end
end

我在configure do 块中使用了enable :logging, :dump_errors, :raise_errors,但这没有任何作用。是不是因为我将 sinatra 用作模块化应用程序?在get "/" 路由中,我可以访问配置块中设置的变量。

那么有什么想法,最好的做法是用 sinatra 将错误记录到文件中吗?

【问题讨论】:

    标签: logging sinatra rack middleware


    【解决方案1】:

    在此处阅读文档:http://www.sinatrarb.com/intro.html#Logging

    请注意,默认情况下仅对 Sinatra::Application 启用日志记录,因此如果您从 Sinatra::Base 继承,您可能需要自己启用它:

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

    【讨论】:

      【解决方案2】:

      我让 Sinatra 将错误消息移动到文件的唯一方法是:

      $stderr.reopen(<the file path>)
      

      更详细的例子:

      class App < Sinatra::Base
        configure do
          set :logging, true
          set :root, File.dirname(__FILE__)
        end
      
        configure :development, :production do
          # console log to file
          log_path = "#{root}/log" 
          Dir.mkdir(log_path) unless File.exist?(log_path)
          log_file = File.new("#{log_path}/#{settings.environment}.log", "a+")
          log_file.sync = true
          $stdout.reopen(log_file)
          $stderr.reopen(log_file)
        end
      end
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 2016-01-21
      • 2018-10-26
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多