Skip to content

Instantly share code, notes, and snippets.

@fogus
Forked from DRMacIver/logging.rb
Created September 14, 2011 12:12
Show Gist options
  • Save fogus/1216406 to your computer and use it in GitHub Desktop.
Save fogus/1216406 to your computer and use it in GitHub Desktop.
Split logging
# Capture stdout and stderr in a named file (while still writing to current stdout and stderr) for a block then restore old behaviour
def capture_output(file)
read, write = IO.pipe
pid = fork
unless pid
write.close
$stdin.reopen(read)
exec "tee", file
end
read.close
oldout = $stdout.dup
olderr = $stderr.dup
begin
$stdout.reopen(write)
$stderr.reopen(write)
$stdout.sync = true
$stderr.sync = true
yield
ensure
$stdout.reopen oldout
$stderr.reopen olderr
write.close
Process.wait pid, Process::WUNTRACED
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment