Ruby: Appending lines to a file in sync

Posted . Visible to the public.

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"
Last edit
Emanuel
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2020-08-21 08:41)