Rotate Log File in Ruby

January 7th, 2007

Sheer laziness has had me scouring the net for a snippet to rotate logs in Ruby (not Rails, everyone already knows about the ole’ config.logger setting). Since I haven’t found anything as of yet, I’ll share my little snippet (and cry about how I spent an hour searching for something that I just wrote in about 4 minutes).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class File
  # Copies excludes the original file
  def self.rotate(filename,copies = 10)
    require 'fileutils'
    raise FileNotFound if !File.exist?(filename)
    return false if copies.to_i < 1
    
    File.unlink "#{filename}.#{copies.to_i - 1}" if File.exist?("#{filename}.#{copies.to_i - 1}")
    (copies.to_i - 2).downto(0) do |n| 
      next if !File.exist?("#{filename}.#{n}")
      File.rename("#{filename}.#{n}","#{filename}.#{n+1}") 
    end
    File.rename filename, "#{filename}.0"
    FileUtils.touch filename
  end
end

Lets say, you want to rotate lighttpd logs for your box and don’t want BSDs log rotater gettin’ its grimy hands on your hard earned traffic logs (don’t ask me anyone would feel that way). Just do this this..

1
2
3
4
# Include aforementioned code
lighttpd_log = "/var/log/lighttpd/lighttpd.access.log
backup_copies = 10
File.rotate lighttpd_log, backup_copies

Simple enough! Moral of the story? If you can’t easily find a snippet, just roll your sleeves, roll a !@#$% and roll your own solution! Thats how we roll!

Leave a Reply

 

Michael Cerna Chicago-based Rails Developer and Avid Musician. More ...

Search

Categories

  • Home (15)
  • Rails Plugins (5)
  • Pages (9)
  • Archives

    Tags

    BlogRoll