Search code examples
taillogrotate

How does "tail -f" and logrotate work?


When I run tail -f for a log file, logrotate rotate it but tail -f did not stop. It continue show logs in new file. After that I try manually;

mv my.log my.log.2
touch my.log
echo "test text" >> my.log
echo "test text" >> my.log

It does not works. How does logrotate rotate logs? Does it copy all lines to new file?

Note: I am working on centos 5.


Solution

  • You may want tail -F instead (uppercase -F) to follow even if the file is deleted, renamed, etc.

      tail -F my.log
    

    tail -f (lowercase) uses the file descriptor only, which doesn't care what the filename is. tail -F uses the filename, so if you delete or rename the original and put a new one in place, it will pickup the new file.

    As for logrotate, it works several different ways. By default, it moves (renames) the original file out of the way, and creates a new empty file. In that case, the file descriptor is maintained for the logging process until it closes and reopens, then it will get the new file.

    If you use the logrotate "copytruncate" option, then both the file and the file descriptor are maintained, and logrotate copies all of the data to a new file, truncates the original file and leaves the original file in place. Some processes do not close their logfile, so using the copytruncate is necessary. Without it, the process will continue to log to the file under its new name.

    This behaviour is by design, in UNIX the file descriptor for an open file is not effected by rename or delete operations.