问题
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