Redirect the "puts" command output to a log file

Josh Moore picture Josh Moore · Oct 22, 2008 · Viewed 23.6k times · Source

I am working on creating a daemon in Ruby using the daemons gem. I want to add output from the daemon into a log file. I am wondering what is the easiest way to redirect puts from the console to a log file.

Answer

Eric Walker picture Eric Walker · Mar 19, 2010

If you need to capture both STDERR and STDOUT and don't want to resort to logging, following is a simple solution adapted from this post:

$stdout.reopen("my.log", "w")
$stdout.sync = true
$stderr.reopen($stdout)