Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

logging

ruby

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.

like image 782
nttstar Avatar asked Dec 18 '11 02:12

nttstar


1 Answers

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
like image 110
Joshua Cheek Avatar answered Sep 21 '22 22:09

Joshua Cheek