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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot
Posted by Emanuel to makandra dev (2020-08-21 10:41)