如何将屏幕上的所有内容记录到文件中?

时间:2013-03-20 00:59:56

标签: ruby logging rubygems

我在Windows上使用一个带rufus/scheduler的rb文件。该脚本在comupter启动时执行,并在cmd窗口中运行。

如何将ruby输出到屏幕的所有内容记录到文件中?我仍然希望能够在屏幕上看到输出。所以我希望记录当前行为。

  • Windows 7 64位
  • ruby​​ 1.9.3p194(2012-04-20)[i386-mingw32]

1 个答案:

答案 0 :(得分:3)

如果您只是希望脚本将输出发送到文件而不是控制台,请使用IO#reopen重定向stdout和stderr。

def redirect_console(filename)
  $stdout.reopen(filename,'w')
  $stderr.reopen(filename,'w')
end

redirect_console('/my/console/output/file')

如果您需要指向一个或多个输出流,请使用代理对象和method_missing发送给他们

class TeeIO
  def initialize(*streams)
    raise ArgumentError, "Can only tee to IO objects" unless streams.all? { |e| e.is_a? IO }
    @streams = streams
  end

  def method_missing(meth, *args)
    # HACK only returns result of first stream
    @streams.map {|io| io.send(meth, *args) }.first
  end

  def respond_to_missing?(meth, include_all)
    @streams.all? {|io| io.respond_to?(meth, include_all) }
  end
end

def tee_console(filename)
  tee_to = File.open(filename, 'w')
  tee_to.sync = true  # flush after each write
  $stdout = TeeIO.new($stdout, tee_to)
  $stderr = TeeIO.new($stderr, tee_to)
end

tee_console('/my/console/output/file')