class Backup::Logger::Logfile

Public Class Methods

new(options) click to toggle source
# File lib/backup/logger/logfile.rb, line 79
def initialize(options)
  @options = options
  @logfile = setup_logfile
  truncate!
end

Public Instance Methods

log(message) click to toggle source
# File lib/backup/logger/logfile.rb, line 85
def log(message)
  File.open(@logfile, 'a') {|f| f.puts message.formatted_lines }
end

Private Instance Methods

setup_logfile() click to toggle source

Returns the full path to the log file, based on the configured @options.log_path, and ensures the path to the log file exists.

# File lib/backup/logger/logfile.rb, line 94
def setup_logfile
  # strip any trailing '/' in case the user supplied this as part of
  # an absolute path, so we can match it against File.expand_path()
  path = @options.log_path.chomp('/')
  if path.empty?
    path = File.join(Backup::Config.root_path, 'log')
  elsif path != File.expand_path(path)
    path = File.join(Backup::Config.root_path, path)
  end
  FileUtils.mkdir_p(path)
  log_file = @options.log_file || 'backup.log'
  path = File.join(path, log_file)
  if File.exist?(path) && !File.writable?(path)
    raise Error, "Log File at '#{ path }' is not writable"
  end
  path
end
truncate!() click to toggle source

Truncates the logfile to @options.max_bytes

# File lib/backup/logger/logfile.rb, line 114
def truncate!
  return unless File.exist?(@logfile)

  if File.stat(@logfile).size > @options.max_bytes
    FileUtils.cp(@logfile, @logfile + '~')
    File.open(@logfile + '~', 'r') do |io_in|
      File.open(@logfile, 'w') do |io_out|
        io_in.seek(-@options.max_bytes, IO::SEEK_END) && io_in.gets
        while line = io_in.gets
          io_out.puts line
        end
      end
    end
    FileUtils.rm_f(@logfile + '~')
  end
end