2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

log4rに日付でローリングしてほしかった話

Last updated at Posted at 2016-02-17

Log4r::DateFileOutputter

日付でファイルを分けることができるが、.changeの中で古いものを消していない

Log4r::RollingFileOutputter

古いものを消してくれるがsequence numberベースでしか名づけられそうにない

そこで

require 'fileutils'

module Log4r

  class RollingDateFileOutputter < Log4r::DateFileOutputter

    def initialize(_name, hash={})
      super(_name, hash)
      @max_files = hash['max_files'] || 5
      @pattern = File.join(File.dirname(@filename),  @filebase.sub(/(.+)\.\w*$/, '\1')) + "*.log"
    end

    def change
      super
      delete_old_logs
    end

    def delete_old_logs
      files = Dir[@pattern].sort_by{ |file|
        File.ctime(file)
      }.reverse.drop(@max_files)
      if files.any?
        FileUtils.rm(files)
      end
    end
  end

end

こんな感じのを書いて、日付ベースで名付けつつ古いものを消すようにしました

設定ファイルは

  outputters:
  - type: RollingDateFileOutputter
    name: file
    level: DEBUG
    date_pattern: '%Y%m%d'
    max_files: 2
    trunc: false
    dirname: "/path/to/log/directory"

こんな感じです。

既存のoutputterの設定次第で同じことできるんですかね?

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?