Rajuk
Rajuk

Reputation: 155

Rails LogRotate files to another directory

I have a rails custom logger in my application.

class ApplicationController < ActionController::API
  @@logger = nil

  def custom_logger
    return @@logger if @@logger
    FileUtils.touch(Rails.root.join('log/custom.json'))
    @@logger = Logger.new(Rails.root.join('log/custom.json'), shift_age = 'daily')
    @@logger.level = Logger::INFO
    @@logger.formatter = proc do |severity, datetime, progname, msg|
      "#{msg}\n"
    end
    @@logger
  end
end

In my application, I can log messages using

custom_logger.info "My log message"

My custom log messages and the rotated files are recorded as follows

Here is my requirement

  1. The rotated files should go in a different location i.e. /<APP_LOCATION>/current/log/archive/custom.json.20210712
  2. The name of the rotated files should also have hour and min, i.e. instead of custom.json.20210712 I need custom.json.202107121020. Format custom.json.{yyyyMMddHHmm,UTC}

Can I do this using Logger class or any other logger gem or write my own logger class by inheriting the Logger class.

Upvotes: 0

Views: 115

Answers (2)

Rajuk
Rajuk

Reputation: 155

Posting solution for the first requirement. The logger does not give us a way to add the rotated files to archive path.

So before returning the logger object I am checking if there are rotated files in the dir. If they are present mv the files to the archive path.

class ApplicationController < ActionController::API
  @@logger = nil

  def custom_logger
    rolled_files = Find.find(Rails.root.join('log').grep(/custom.json.[\d]{12}/)
    mv_rolled_files(rolled_files) if !rolled_files.empty?
    return @@logger if @@logger
    FileUtils.touch(Rails.root.join('log/custom.json'))
    @@logger = Logger.new(Rails.root.join('log/custom.json'), shift_age = 'daily')
    @@logger.level = Logger::INFO
    @@logger.formatter = proc do |severity, datetime, progname, msg|
      "#{msg}\n"
    end
    @@logger
  end

  private

  def mv_rolled_files(rolled_files)
    # Move rotated files to an archive location.
  end
end

I know this is not an efficient way. I will go with the current approach for now until I find a better way to do it.

Upvotes: 0

Sukeerthi Adiga
Sukeerthi Adiga

Reputation: 589

The first requirement to put only the archived logs in a different path isn't possible while instantiating the Logger. Alternate to this is using a cronjob or a background job.

And, the second requirement on changing the file name is doable by passing the shift_period_suffix key in the options.

    @@logger = Logger.new(Rails.root.join('log/custom.json'), shift_age = 'daily', shift_period_suffix: "%Y%m%d%H%m, %Z")

Upvotes: 1

Related Questions