Created
September 14, 2011 10:50
-
-
Save DRMacIver/1216300 to your computer and use it in GitHub Desktop.
Split logging
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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