Skip to content

Instantly share code, notes, and snippets.

@jqr
Created February 24, 2012 01:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jqr/1896642 to your computer and use it in GitHub Desktop.
Save jqr/1896642 to your computer and use it in GitHub Desktop.
Locking log rotation for processing
require 'fileutils'
class Reader
def self.read(filename, processing_filename)
return [] unless File.exists?(filename)
FileUtils.move(filename, processing_filename)
lines = []
File.open(processing_filename, 'r') do |f|
f.flock(File::LOCK_EX)
while !f.eof?
lines << f.gets.chomp
end
end
FileUtils.rm(processing_filename)
lines
end
end
lines = Reader.read('log', 'processing')
puts "Captured %4i lines: %4i - %4i" % [lines.size, lines[0], lines[-1]]
class Writer
def initialize(filename, ttl)
@filename = filename
@ttl = ttl
reopen
end
def reopen
@next_open_at = Time.now + @ttl
@file.close if @file
@file = File.open(@filename, 'a+')
@file.flock(File::LOCK_SH)
end
def write(data)
reopen if Time.now > @next_open_at
@file.write(data)
@file.flush
end
end
w = Writer.new('log', 3)
i = 0
loop do
i += 1
w.write("#{i}\n")
puts i
sleep 0.5
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment