nttstar
nttstar

Reputation: 341

Why doesn't Logger output to STDOUT get redirected to files?

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.

Upvotes: 6

Views: 5214

Answers (1)

Joshua Cheek
Joshua Cheek

Reputation: 31726

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

Upvotes: 13

Related Questions