Created
February 24, 2012 01:53
-
-
Save jqr/1896642 to your computer and use it in GitHub Desktop.
Locking log rotation for processing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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