简体   繁体   English

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

[英]How to log everything on the screen to a file?

I use one rb file with rufus/scheduler on Windows. 我在Windows上使用rufus/scheduler使用一个rb文件。 The script is executed on a comupter start up and it runs in a cmd window. 该脚本在计算机启动时执行,并在cmd窗口中运行。

How can I log everything that ruby outputs to the screen to a file? 如何将ruby输出到屏幕的所有内容记录到文件中? 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 Windows 7 64位
  • ruby 1.9.3p194 (2012-04-20) [i386-mingw32] 红宝石1.9.3p194(2012-04-20)[i386-mingw32]

If you just want the script to send output to the file instead of the console use IO#reopen to redirect stdout and stderr. 如果只希望脚本将输出发送到文件而不是控制台,请使用IO#reopen重定向stdout和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 如果您需要定向到一个或多个输出流,请使用代理对象和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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM