Skip to content

Instantly share code, notes, and snippets.

@mperham
Created February 15, 2010 15:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mperham/304739 to your computer and use it in GitHub Desktop.
Save mperham/304739 to your computer and use it in GitHub Desktop.
task :logrotate do
require 'erb'
upload_path = "#{shared_path}/system/logrotate"
template = File.read("deploy/logrotate.erb")
file = ERB.new(template).result(binding)
put file, upload_path, :mode => 0644
run "if [ -e /etc/logrotate.d ]; then sudo cp #{shared_path}/system/logrotate /etc/logrotate.d/#{name}; fi"
end
after 'deploy:symlink', 'deploy:logrotate'
# Stolen from Unicorn::Util
#
# This reopens ALL logfiles in the process that have been rotated
# using logrotate(8) (without copytruncate) or similar tools.
# A +File+ object is considered for reopening if it is:
# 1) opened with the O_APPEND and O_WRONLY flags
# 2) opened with an absolute path (starts with "/")
# 3) the current open file handle does not match its original open path
# 4) unbuffered (as far as userspace buffering goes, not O_SYNC)
# Returns the number of files reopened
def reopen_logs
nr = 0
append_flags = File::WRONLY | File::APPEND
Rails.logger.info "Rotating logs"
#logs = [STDOUT, STDERR]
#logs.each do |fp|
ObjectSpace.each_object(File) do |fp|
next if fp.closed?
next unless (fp.sync && fp.path[0..0] == "/")
next unless (fp.fcntl(Fcntl::F_GETFL) & append_flags) == append_flags
begin
a, b = fp.stat, File.stat(fp.path)
next if a.ino == b.ino && a.dev == b.dev
rescue Errno::ENOENT
end
open_arg = 'a'
if fp.respond_to?(:external_encoding) && enc = fp.external_encoding
open_arg << ":#{enc.to_s}"
enc = fp.internal_encoding and open_arg << ":#{enc.to_s}"
end
Rails.logger.info "Rotating path: #{fp.path}"
fp.reopen(fp.path, open_arg)
fp.sync = true
nr += 1
end # each_object
nr
end
Signal.trap("HUP") { reopen_logs }
<%= shared_path %>/log/*.log {
daily
missingok
compress
rotate 7
sharedscripts
postrotate
for i in <%= shared_path %>/pids/*.pid; do
kill -HUP `cat $i`
done
endscript
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment