6

This script is named o.rb:

@logger = Logger.new(STDOUT)
@logger.info "start_time : #{start_time}"

When I run it using ./o.rb, the output on the console is correct.
However, when I tried ./o.rb > log.txt 2>&1, the log file is empty!
Why did this happen?

I have the same issue while using the simple puts function.


UPDATE

This will reproduce this issue:

require 'logger'

logger = Logger.new(STDOUT)

loop do
  logger.info "This is a test haha"
  sleep(1)
end

When I run it using ./foo.rb, it writes correctly to the console output.

When I run ./foo.rb > log.txt, I get nothing.

Also, when I use ./foo.rb | tee log.txt, nothing is written to the console and the log file is empty.

The log.txt file was created but remains empty.

My Ruby version is 1.8.7.

6
  • My program will keeps running maybe for 1 day, is it caused by the file buffers not flushed? Just now I write a simple script that only output one sentence and the program exit, it works. Commented Dec 18, 2011 at 3:14
  • I don't think it is buffering; LogDevice::new calls @dev.sync = true -- which asks for unbuffered operation. Commented Dec 18, 2011 at 3:47
  • Do you have permission to write to that file (or the containing directory, if the file doesn't already exist)? Commented Dec 18, 2011 at 4:13
  • I have the permission. Not only the Logger but also 'puts', My program will output 1 sentence per 10 seconds on console. But when I redirect it to file by '>' or 'tee', and wait for 1 minute, NOTHING! I feel very strange. Commented Dec 18, 2011 at 4:53
  • Can you make a very simple program that we can run to reproduce the problem? Commented Dec 18, 2011 at 5:06

1 Answer 1

13

It's a buffering problem, you can set the standard output to sync and this should resolve it.

#!/usr/bin/env ruby

require 'logger'

$stdout.sync = true
logger = Logger.new($stdout)

loop do
  logger.info "This is a test haha"
  sleep 1
end
Sign up to request clarification or add additional context in comments.

2 Comments

it works. but why outputting to console does not have this issue(without redirecting)?
Not sure, Bash must buffer the file descriptor when standard output isn't a tty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.