Skip to content

Instantly share code, notes, and snippets.

@myobie
Last active August 29, 2015 14:12
Show Gist options
  • Save myobie/db9ca868415873f0d8be to your computer and use it in GitHub Desktop.
Save myobie/db9ca868415873f0d8be to your computer and use it in GitHub Desktop.
I wrote my own log rotator...for reasons...
#!/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