Skip to content

Instantly share code, notes, and snippets.

@pocari
Created April 7, 2022 18:10
Show Gist options
  • Save pocari/fedd5da1b52fff110e22bd63fb2715bd to your computer and use it in GitHub Desktop.
Save pocari/fedd5da1b52fff110e22bd63fb2715bd to your computer and use it in GitHub Desktop.
signal をつけて reopen するlogger logrotate ローテーション
require 'pry-byebug'
require 'logger'
pid_file = '/home/pocari/tmp/logrotate/sample_daemon.pid'
File.open(pid_file, "w") { |f| f.write "#{Process.pid}" }
at_exit do
if File.exists?(pid_file)
File.delete(pid_file)
end
end
class MyLogger < Logger
attr_reader :logdev
def initialize(*args, **kwargs)
super
end
end
logger = MyLogger.new('/home/pocari/tmp/logrotate/output.log')
trap("USR1") do
p [:trapped, :USR1]
# signalハンドラの制限でreopenできないため、フラグだけ立てる
$reopen_flag = true
end
500.times do |i|
if $reopen_flag
# これが立っていたらログローテートされているので、新しいファイルをreopenする
logger.reopen
$reopen_flag = false
end
logger.info("i ... #{i}")
sleep 0.1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment