Last active
August 29, 2015 14:12
-
-
Save myobie/db9ca868415873f0d8be to your computer and use it in GitHub Desktop.
I wrote my own log rotator...for reasons...
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
#!/usr/bin/ruby | |
require "fileutils" | |
ROTATE = ENV.fetch("ROTATE", 52).to_i | |
VERBOSE = ENV.fetch("VERBOSE", "false") == "true" | |
file = ARGV[0] | |
puts "Rotating #{file}..." if VERBOSE | |
current_time = Time.now.to_f.to_s | |
new_file = "#{File.dirname(file)}/#{File.basename(file)}.#{current_time}#{File.extname(file)}" | |
puts "To #{new_file}..." if VERBOSE | |
FileUtils.copy(file, new_file) | |
puts "Copied." if VERBOSE | |
File.open(file, "w+") { |f| f.truncate(0) } | |
puts "Truncated." if VERBOSE | |
pattern = "#{File.dirname(file)}/#{File.basename(file)}.*#{File.extname(file)}" | |
all_files = Dir[pattern].sort | |
exit 0 unless all_files.size > ROTATE | |
puts "More than #{ROTATE}..." if VERBOSE | |
first = all_files.take(ROTATE) | |
left_overs = all_files - first | |
puts "rm'ing #{left_overs.size} files..." if VERBOSE | |
left_overs.each { |j| FileUtils.rm(j) } | |
puts "Done." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment