Class: NginxUtils::Logrotate

Inherits:
Object
  • Object
show all
Defined in:
lib/nginx_utils/logrotate.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Logrotate

Returns a new instance of Logrotate.



9
10
11
# File 'lib/nginx_utils/logrotate.rb', line 9

def initialize(options={})
  configure(options)
end

Instance Attribute Details

#delete_logsObject

Returns the value of attribute delete_logs.



7
8
9
# File 'lib/nginx_utils/logrotate.rb', line 7

def delete_logs
  @delete_logs
end

#loggerObject

Returns the value of attribute logger.



5
6
7
# File 'lib/nginx_utils/logrotate.rb', line 5

def logger
  @logger
end

#rename_logsObject

Returns the value of attribute rename_logs.



6
7
8
# File 'lib/nginx_utils/logrotate.rb', line 6

def rename_logs
  @rename_logs
end

Instance Method Details

#config(options = {}) ⇒ Object



13
14
15
# File 'lib/nginx_utils/logrotate.rb', line 13

def config(options={})
  configure(options)
end

#deleteObject



29
30
31
32
33
34
35
36
37
38
# File 'lib/nginx_utils/logrotate.rb', line 29

def delete
  retention_time = Time.now - (@params[:retention].to_i * 3600 * 24)

  @delete_logs.each do |log|
    if File.stat(log).mtime < retention_time
      File.unlink(log) if @execute
      @logger.debug "Delete log file: #{log}" if @logger
    end
  end
end

#executeObject



57
58
59
60
61
62
63
# File 'lib/nginx_utils/logrotate.rb', line 57

def execute
  @logger.info "Execute Nginx logrotate" if @logger
  rename
  delete
  @logger.info "Nginx logrotate is successfully" if @logger
  restart
end

#renameObject



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/nginx_utils/logrotate.rb', line 17

def rename
  @rename_logs.each do |log|
    after = "#{log}.#{@params[:prefix]}"
    if File.exists? after
      @logger.warn "File already exists: #{after}" if @logger
    else
      File.rename(log, after) if @execute
      @logger.debug "Rename log file: #{log} to #{after}" if @logger
    end
  end
end

#restartObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/nginx_utils/logrotate.rb', line 40

def restart
  if File.exists? @params[:pid_file]
    if @execute
      begin
        Process.kill(:USR1, File.read(@params[:pid_file]).to_i)
        @logger.info "Nginx restart is successfully" if @logger
      rescue => e
        @logger.error "Nginx restart failed" if @logger
        @logger.error e if @logger
        raise "Nginx restart failed"
      end
    end
  else
    @logger.warn "Pid file is not found. Do not restart nginx." if @logger
  end
end