umut
umut

Reputation: 1026

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.

Upvotes: 8

Views: 3880

Answers (2)

mrjoltcola
mrjoltcola

Reputation: 20842

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.

Upvotes: 7

user353608
user353608

Reputation:

To know the answer to this you need to know what logrotate is doing with the file. From the tail man page

With --follow (-f), tail defaults to following the file descriptor, which means that even if a tail’ed file is renamed, tail will continue to track its end. This default behavior is not desirable when you really want to track the actual name of the file, not the file descriptor (e.g., log rotation). Use --follow=name in that case. That causes tail to track the named file in a way that accommodates renaming, removal and creation.

What you're seeing would suggest that the fd is not changing when logrotate acts upon the file so it is likely using the copytruncate method.

Upvotes: 4

Related Questions