【问题标题】:How to capture output produced with 'puts' inside a script and save it to a file in ruby/rails?如何捕获在脚本中使用“puts”产生的输出并将其保存到 ruby​​/rails 中的文件中?
【发布时间】:2011-06-21 10:41:54
【问题描述】:

从我在 Rails 应用程序中的脚本/目录中,我试图捕获从 lib 文件生成的输出,而不是在屏幕上显示它,我希望将其保存到文件中。我有一个脚本,它应该在调用“puts”时将输出显示到屏幕上,但在调用产生输出的方法之前,它应该设置一些东西,以便调用的函数在使用 puts 时应该记录到文件中。我一直在我的 rails 应用程序中试验以下两个文件,但它们似乎不起作用。 (stderr 输出被正确捕获到文件中,但是在下面的代码中,通过简单调用“puts”产生的 otuput 没有保存到文件“a.log”中:)

#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require File.join(RAILS_ROOT, 'lib/mylogger.rb')

puts "logtest" # should output logtest on the screen

STDERR.puts "logtest" # should also output on the screen

x = STDOUT
y = STDERR
STDOUT = File.new("a.log", "w")
STDERR = File.new("b.log", "w")
m = MyLogger.new
m.run
STDOUT = x
STDERR = y
puts "logtest" # should log to the screen
STDERR.puts "logtest" # should log to the screen

而mylogger.rb文件如下:

class MyLogger

  def run
    1.upto 1_000_000 do |x|
      puts "mylogger #{x}" # should log to the file a.log, this does not work
      STDERR.puts "mylogger #{x}" # should log to the file b.log, this works
    end
  end
end

【问题讨论】:

标签: ruby-on-rails ruby logging


【解决方案1】:

$stdout.reopen(File.open("a.log", "w"))

【讨论】:

    【解决方案2】:

    我换行了

    STDOUT = File.new("a.log", "w")
    

    $stdout = File.new("a.log", "w")
    

    我变了

    STDOUT = x
    

    $stdout = STDOUT
    

    成功了

    【讨论】:

      猜你喜欢
      • 2014-11-07
      • 1970-01-01
      • 1970-01-01
      • 2011-06-10
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      相关资源
      最近更新 更多