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

34,820

Solution 1

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

Solution 2

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")

Solution 3

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

Solution 4

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

will redirect stdout and stderr to the same file.

Solution 5

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"
Share:
34,820

Related videos on Youtube

AOO
Author by

AOO

Updated on July 09, 2022

Comments

  • AOO
    AOO almost 2 years

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

  • Steve Weet
    Steve Weet almost 14 years
    Assuming you are running on *nix
  • oligan
    oligan about 13 years
    @Steve: I think > works on Windows - I'm not sure about 2> though.
  • silvamerica
    silvamerica almost 13 years
    What do you mean by "helping a process become a daemon"?
  • argent_smith
    argent_smith almost 13 years
    In UNIX in order to make a program a daemon the programmer should not merely fork it into background but also redirect it's standard IO streams. Are you familiar with this?
  • Daisy Sophia Hollman
    Daisy Sophia Hollman over 12 years
    This answer also makes assumptions about what shell the user is using, even within *nix. Some shells have different redirection styles, for instance the default behavior of zsh.
  • Kyle Heironimus
    Kyle Heironimus almost 11 years
    Good, but this is better, in case STDOUT was something else. stackoverflow.com/a/4459463/26604
  • captainpete
    captainpete over 8 years
    Note: If using built-in Process.daemon it can do this for you. See docs here.

Related