Create only one log every day using Ruby standard Logger

I use a ruby ​​standard logger, I want it to rotate every day, so in my code I have:

Logger.new("#{$ROOT_PATH}/log/errors.log", 'daily')  

It works fine, but it created two files errors.log.20130217and errors.log.20130217.1.

How can I make it create only one file per day?

+5
source share
1 answer

Your code is correct for a long-term application.

What happens, you use the code more than once on a specific day.

The first time Ruby starts, it creates the log file "errors.log".

When the day changes, Ruby renames the file to "errors.log.20130217".

- , , ( , ), , , "errors.log.20130217" ,

, "errors.log" , "errors.log.20130217.1"

, .

"foo" "bar", , "foo-errors.log" "bar-errors.log". , , (, , , ).

Ruby, #shift_log_period, ".1". Logger worn #shift_log_period, , , , , .

, :

def shift_log_period(period_end)
  postfix = period_end.strftime("%Y%m%d") # YYYYMMDD
  age_file = "#{@filename}.#{postfix}"
  if FileTest.exist?(age_file)
    # try to avoid filename crash caused by Timestamp change.
    idx = 0
    # .99 can be overridden; avoid too much file search with 'loop do'
    while idx < 100
      idx += 1
      age_file = "#{@filename}.#{postfix}.#{idx}"
      break unless FileTest.exist?(age_file)
    end
  end
  @dev.close rescue nil
  File.rename("#{@filename}", age_file)
  @dev = create_logfile(@filename)
  return true

(AFAIK) , (, , ), . , .

, logrotate, Tin Man : http://linuxcommand.org/man_pages/logrotate8.html

, logrotate IMHO.

+11

All Articles