-
-
Save ph/381c51832c7174827636 to your computer and use it in GitHub Desktop.
This file contains 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 "thread" | |
require 'fileutils' | |
DUMMY_CONTENT = "hello" | |
class LogSample | |
def initialize(path) | |
@path = path | |
end | |
def create | |
name = filename | |
File.open(name, "w+") do |f| | |
f.write("#{DUMMY_CONTENT}\n") | |
end | |
return name | |
end | |
def filename | |
File.join(@path, "mylog_#{Time.now.to_i}.log") | |
end | |
def self.create(path) | |
new(path).create | |
end | |
end | |
###### | |
class LogMaker | |
ACTIONS =[ | |
:CREATE, | |
:DELETE, | |
] | |
# create files | |
# delete file | |
# rotate file | |
def initialize(path) | |
@path = File.expand_path(path) | |
@files = {} | |
end | |
def start | |
loop do | |
send(random_action) | |
sleep(10) | |
end | |
end | |
def create | |
new_file = LogSample.create(@path) | |
puts "CREATE: #{new_file}" | |
@files[new_file] = true | |
end | |
def write | |
file = random_file | |
return unless file | |
puts "WRITE: #{file}" | |
File.open(file, "a") do |fd| | |
100.times.each {|i| fd.write("#{DUMMY_CONTENT}\n") } | |
end | |
end | |
def delete | |
if @files.values.size > 0 | |
file = random_file | |
@files.delete(file) | |
puts "DELETE: #{file}" | |
FileUtils.rm_rf(file) | |
end | |
end | |
def random_file | |
@files.keys.sample | |
end | |
def rotate | |
if @files.values.size > 0 | |
file = random_file | |
return if file =~ /_backup/ | |
@files.delete(file) | |
new_name = "#{file}_backup" | |
puts "ROTATE: #{file} TO #{new_name}" | |
File.rename(file, new_name) | |
@files[new_name] = true | |
end | |
end | |
def random_action | |
ACTIONS[rand(ACTIONS.size)].to_s.downcase | |
end | |
def self.clean_files(path) | |
Dir.glob(File.join(File.expand_path(path), "**")).each do |f| | |
puts "CLEANING: #{f}" | |
FileUtils.rm_rf(f) | |
end | |
end | |
end | |
## | |
## | |
# | |
Thread.abort_on_exception = true | |
LogMaker.clean_files("../logs") | |
maker = LogMaker.new("../logs") | |
t = Thread.new(maker) {|maker| maker.start } | |
t.join | |
#require 'filewatch/tail' | |
#t = FileWatch::Tail.new | |
#t.tail("logs2/*.log") | |
#t.subscribe { |path, line| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment