2011-05-12 55 views
0

当我做$stdout.puts "foo"时,我希望它转到stdout和文件。将标准从流程复制到标准输出和文件的最佳方式是什么?

我想出了:

def log_init 
    $stdout.sync = true 
    old_out = $stdout.dup 
    old_out.sync = true 
    r, w = IO.pipe 
    $stdout.reopen(w) 
    fork do 
    f = File.open('/tmp/test', 'a') do |f| 
     f.sync = true 
     while (sel = IO.select([r], [], [], 1000)) 
     readfds, *rest = sel 
     data = readfds.first.readpartial(1024) 
     old_out.write(data) 
     f.write(data) 
     end 
    end 
    end 
end 

你能做到这一点,而不需要第二个过程?

回答

2

只要做到这一点从壳:

your-program | tee file 
0

我想从Ruby的邮件列表这篇文章/线程可能会帮助你前进:http://www.ruby-forum.com/topic/102759#226506

尤其是这一段代码:

["$stdout", "$stderr"].each do |std| 
    io   = eval(std) 
    old_write = io.method(:write) 

    class << io 
    self 
    end.module_eval do 
    define_method(:write) do |text| 
     unless text =~ /^[\r\n]+$/  # Because puts calls twice. 
     File.open("logfile.log", "a") do |f| 
      f.puts [std[1..-1].upcase, caller[2], text].join(" ") 
     end 
     end 

     old_write.call(text) 
    end 
    end 
end 

$stdout.puts "text on stdout" 
$stderr.puts "text on stderr" 
相关问题