How do tail -f and logrotate work?

When I run tail -f for the log file, logrotate rotates it, but tail -f does not stop. He continues to show the logs in a new file. After that I will try manually:

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

This does not work. How does logrotate rotate logs? Will all lines be copied to a new file?

Note. I am working on centos 5.

+7
tail logrotate
source share
2 answers

You may need tail -F instead (upper case -F), even if the file is deleted, renamed, etc.

  tail -F my.log 

tail -f (lowercase) uses only a file descriptor that does not care about what the file name is. tail -F uses the file name, so if you delete or rename the original and put a new one in place, it will write a new file.

As for logrotate, it works differently. By default, it moves (renames) the source file to the side and creates a new empty file. In this case, the file descriptor is maintained for the logging process until it closes and opens, and it receives a new file.

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

This design behavior is that on UNIX, the file descriptor for an open file is not performed using rename or delete operations.

+5
source share

To find out the answer to this question, you need to know what logrotate does with the file. On the tail page

With --follow (-f), the tail follows the file descriptor by default, which means that even if the tail file is renamed, the tail will continue to track its end. This default behavior is undesirable if you really want to keep track of the actual file name and not the file descriptor (for example, log rotation). In this case, use --follow = name. This causes the tail to track the named file in a way that accommodates renaming, deletion, and creation.

What you see suggests that fd does not change when logrotate acts on the file, so it probably uses the copytruncate method.

+4
source share

All Articles