Read more

Ruby: Appending lines to a file in sync

Emanuel
August 21, 2020Software engineer at makandra GmbH

When writing some logs to a file, that don't use Ruby's logger utility Show archive.org snapshot , it is often useful to sync them. So other process can read the output just in time.

Example with enabled sync

log_path = '/tmp/some_log.log'

log_file = File.open(log_path, 'a+')
log_file.sync = true

log_file.puts('Some log message')
File.read(log_path) #=> "Some log message\n"

log_file.puts('Some other message')
File.read(log_path) #=> "Some log message\nSome other message\n"

Example with disabled sync (default)

log_path = '/tmp/some_log.log'

log_file = File.open(log_path, 'a+')

log_file.puts('Some log message')
File.read(log_path) #=> ""

log_file.puts('Some other message')
File.read(log_path) #=> ""

log_file.close # Which is also called by the garbage collector once the file is safe to close
File.read(log_path) #=> "Some log message\nSome other message\n"
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot
Posted by Emanuel to makandra dev (2020-08-21 10:41)