Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reopen log file when rotation is detected #127

Merged
merged 1 commit into from
Jun 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions lib/serverengine/daemon_logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ def logdev=(logdev)
# update path string
old_file_dev = @file_dev
@file_dev = LogDevice.new(logdev, shift_age: @rotate_age, shift_size: @rotate_size)
# Enable to detect rotation done by external tools.
# Otherwise it continues writing logs to old file unexpectedly.
@file_dev.extend(RotationAware)
old_file_dev.close if old_file_dev
ashie marked this conversation as resolved.
Show resolved Hide resolved
@logdev = @file_dev
end
Expand Down Expand Up @@ -130,6 +133,40 @@ def close
nil
end

module RotationAware
def self.extended(obj)
obj.update_ino
end

def update_ino
(@ino_mutex ||= Mutex.new).synchronize do
@ino = File.stat(filename).ino rescue nil
@last_ino_time = Time.now
end
end

def reopen(log = nil)
super(log)
update_ino
end

def reopen!
super
update_ino
end

def write(message)
reopen_needed = false
@ino_mutex.synchronize do
if (Time.now - @last_ino_time).abs > 1
ino = File.stat(filename).ino rescue nil
reopen_needed = true if ino && ino != @ino
end
end
reopen! if reopen_needed
super(message)
end
end
end

end
25 changes: 25 additions & 0 deletions spec/daemon_logger_spec.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'stringio'
require 'timecop'

describe ServerEngine::DaemonLogger do
before { FileUtils.rm_rf("tmp") }
Expand Down Expand Up @@ -172,4 +173,28 @@
$stderr = STDERR
stderr.should_not =~ /(log shifting failed|log writing failed|log rotation inter-process lock failed)/
end

it 'reopen log when path is renamed' do
pending "rename isn't supported on windows" if ServerEngine.windows?

log = DaemonLogger.new("tmp/rotate.log", { level: 'info', log_rotate_age: 0 })

log.info '11111'
File.read("tmp/rotate.log").should include('11111')
File.rename("tmp/rotate.log", "tmp/rotate.log.1")

Timecop.travel(Time.now + 1)

log.info '22222'
contents = File.read("tmp/rotate.log.1")
contents.should include('11111')
contents.should include('22222')

FileUtils.touch("tmp/rotate.log")
Timecop.travel(Time.now + 1)

log.info '33333'
File.read("tmp/rotate.log").should include('33333')
File.read("tmp/rotate.log.1").should_not include('33333')
end
end