AOO
AOO

Reputation: 481

How do I redirect stderr and stdout to file for a Ruby script?

How do I redirect stderr and stdout to file for a Ruby script?

Upvotes: 48

Views: 38270

Answers (5)

Atika
Atika

Reputation: 1618

A full example with $stdout and $stderr redirected to a file and how to restore the initial behavior.

#!/usr/bin/ruby

logfile = "/tmp/testruby.log"

@original_stdout = $stderr.dup
@original_stderr = $stderr.dup
$stdout.reopen(logfile, "w")
$stdout.sync = true
$stderr.reopen($stdout)


def restore_stdout
  $stdout.reopen(@original_stdout)
  $stderr.reopen(@original_stderr)
end

def fail_exit(msg)
  puts "- #{msg}" # to the logfile
  restore_stdout
  $stderr.puts "+ #{msg}" # to standard error
  exit!
end

def success_exit(msg)
  puts "- #{msg}" # to the logfile
  restore_stdout  
  $stdout.puts "+ #{msg}" # to standard output
  exit
end

puts "This message goes to the file"

success_exit "A successful exit message"

Upvotes: 3

grosser
grosser

Reputation: 15097

def silence_stdout
  $stdout = File.new( '/dev/null', 'w' )
  yield
ensure
  $stdout = STDOUT
end

Upvotes: 10

argent_smith
argent_smith

Reputation: 486

Note: reopening of the standard streams to /dev/null is a good old method of helping a process to become a daemon. For example:

# daemon.rb
$stdout.reopen("/dev/null", "w")
$stderr.reopen("/dev/null", "w")

Upvotes: 13

Mark Rushakoff
Mark Rushakoff

Reputation: 258138

From within a Ruby script, you can redirect stdout and stderr with the IO#reopen method.

# a.rb
$stdout.reopen("out.txt", "w")
$stderr.reopen("err.txt", "w")

puts 'normal output'
warn 'something to stderr'
$ ls
a.rb
$ ruby a.rb
$ ls
a.rb    err.txt out.txt
$ cat err.txt 
something to stderr
$ cat out.txt 
normal output

Upvotes: 70

Richard Fearn
Richard Fearn

Reputation: 25491

./yourscript.rb 2>&1 > log.txt

will redirect stdout and stderr to the same file.

Upvotes: 4

Related Questions