Video in progress
A service opens and writes its own log file. After logrotate moves the file, the new log stays empty while the disk keeps filling up. Why does this happen, and how do you solve it?
Java writes to the inode through an open descriptor, not to the file name. After mv it keeps writing to the old, rotated file; if that gets deleted, it is deleted but still open, and the space isn't freed. The solutions: leave rotation to the logger itself, use copytruncate, or have a reopen mechanism.
📖 Answer
On Unix a file name is just a link to an inode in a directory. When FileOutputStream is opened, the process holds the inode. logrotate renames app.log to app.log.1: the inode is the same, only the name differs. The service keeps writing to app.log.1, and the new empty app.log is of no use to anyone. At the next rotation, if app.log.1 is deleted, du doesn't see it while df says the space is used.
lsof -p $PID | grep deleted # deleted but still open files
lsof +L1 # open files with a link count of 0
The solutions, in the order I prefer:
-
The logger does the rotation. Logback's
RollingFileAppenderor Log4j2'sRollingFileAppendercloses the file, renames it and opens a new one by itself. External logrotate doesn't touch these files. -
In a container, stdout. There is no file at all, and rotation is the container runtime's job.
-
copytruncate. logrotate copies the file and truncates the original to zero. There are two catches: lines written between the copy and the truncate are lost; and if the writer didn't open the file withAPPEND, it keeps writing from its old offset, and a "hole" of gigabytes of zero bytes (a sparse file) appears at the start of the file. In Java,StandardOpenOption.APPENDornew FileOutputStream(f, true)is a must. -
Reopening. If you wrote the writer yourself, you periodically check the file's identifier by name and reopen if it changed:
Object current = Files.readAttributes(path, BasicFileAttributes.class).fileKey(); // (dev, ino) on Linux
if (!current.equals(openedKey)) reopen();
Java has no official API for catching SIGHUP, so instead of "reopen on a signal" like in nginx, this kind of check or a management endpoint is used.
The same inode logic shows up elsewhere: when a configuration file is replaced with rename, an old descriptor keeps reading the old content, and tail -f doesn't see the new file (tail -F does).
Sign up to mark studied questions and save your progress.