DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Optimize File Log

03.19.2012
| 3521 views |
  • submit to reddit
        Optimize openning file trace for log:

$logq   = Queue.new
$log_fn = "/tmp/trace.log"
def log(*res) 
  mess= "%s | %s" % [Time.now.strftime("%Y-%m-%d %H:%M:%S"),res.join(" ")]
  $logq.push(mess) if $logq.size<10000
end
Thread.new do
  loop do
     sleep 10
     File.open($log_fn,"a") { |f| f.puts( $logq.pop) while $logq.size>0 } if $logq.size>0
  end
end

Or this one is perhaps better :

Thread.new do
  loop do
     m=$logq.pop
     sleep 3
     File.open($log_fn,"a") { |f| 
		f.puts( m)
		f.puts( $logq.pop) while $logq.size>0 
	 } if m
  end
end

And then, for good exit:

$th=Thread.new ...
at_exit { 
   $th.kill rescue nil
   logger("exit")
   File.open($log_fn,"a") { |f| f.puts( $logq.pop) while $logq.size>0 } if $logq.size>0
}