Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove logs older than 90 day

Tags:

ruby

I am writing a script that will zip up logs and remove anything older than 90 days on a Windows 2008 Server. I have come close by doing the following:

def remove_old_logs()
  d = Time.now.localtime.strftime("%m-%d-%Y")
  tfile = "c:/slog/sec/Archive/#{d}-logs.zip"
  mtme=File.stat(tfile).mtime.to_s.split[0]

  # Compare the old mtime with the old and remove the old.
  Dir["c:/slog/sec/Archive/*"].each do |file|
    ntme=File.stat(file).mtime.to_s.split[0]
    FileUtils.rm( file ) if mtme > ntme #'Time.now.localtime.strftime("%Y-%m-%d")'
  end
end

What would I have to do to get Ruby to do the Linux equivalent of:

find . -mtime +90 -type f -exec rm {} \;
like image 745
Jay Avatar asked Dec 19 '25 23:12

Jay


2 Answers

Here's a somewhat idiomatic Ruby way that is OS independent,

require 'date'

module Enumerable
  def older_than_days(days)
    now = Date.today
    each do |file|
      yield file if (now - File.stat(file).mtime.to_date) > days
    end
  end
end

# Example emulating `find /path/to... -mtime +90 -type f -exec rm {} \;`
Dir.glob('/path/to/your/files/**/*').older_than_days(90) do |file|
  FileUtils.rm(file) if File.file?(file)
end

Note use of Dir.glob's ** to match recursively.

(Incidentally you might consider in shell, find . -mtime +90 -type f -print0 | xargs -0 rm to be more efficient and avoid the separator problem)

like image 167
tantrix Avatar answered Dec 21 '25 18:12

tantrix


What is it your script isn't doing that you want? The only significant thing I see that is missing is the test to see if it's a file or directory, -type f in the find command.

File.file?('path/to/file')

The only other thing is the test to see if it's older than 90 days, but you should be able to figure that out easily enough.

like image 22
the Tin Man Avatar answered Dec 21 '25 18:12

the Tin Man