How to log everything on the screen to a file?

霸气de小男生 提交于 2020-01-07 05:35:05

问题


I use one rb file with rufus/scheduler on Windows. The script is executed on a comupter start up and it runs in a cmd window.

How can I log everything that ruby outputs to the screen to a file? I still want to be able to see the output on the screen. So I want the logging on top of current behaviour.

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

回答1:


If you just want the script to send output to the file instead of the console use IO#reopen to redirect stdout and stderr.

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

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

If you need to direct to one or more output streams, use a proxy object and method_missing to send to them

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')


来源:https://stackoverflow.com/questions/15513403/how-to-log-everything-on-the-screen-to-a-file

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