Sha256: 80d9ec4a65e2d6bcb0b630627d7c899b0b477d7d11a1ac0e7ca882626fe6105d

Contents?: true

Size: 927 Bytes

Versions: 1

Compression:

Stored size: 927 Bytes

Contents

# frozen_string_literal: true

require "log_sweeper/version"

require "shellwords"
require "pathname"
require "logger"

module LogSweeper
  extend self

  def run(path, logs_lifetime_days_count: 10, logger: Logger.new(STDOUT))
    min_mtime = Time.now - (logs_lifetime_days_count.to_f * 24 * 3600)

    Pathname.new(path).each_child do |entry|
      next unless entry.file?

      filename = entry.basename.to_s

      if filename.match?(/\.log\b/) && entry.mtime < min_mtime
        logger.info "deleting #{entry}"
        entry.delete
      elsif filename.match?(/\.log\.\d+$/)
        logger.info "gzipping #{entry}"
        compress_file(entry)
        entry.delete
      else
        logger.info "skipping #{entry}"
      end
    end

    true
  end

  private

  def compress_file(file_name)
    zipped = "#{file_name}.gz"

    Zlib::GzipWriter.open(zipped) do |gz|
      gz.write IO.binread(file_name)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
log_sweeper-1.0.0 lib/log_sweeper.rb