The story is there is a log file that will be rotated repeatedly by some interval. I need to write a small tool in Python that always print new logs in that file even after it rotated. How can I tell the old log file is renamed, and open the new one in Python?
-
1What does rotated mean? How does this change the file name? – Tim Jun 20 '14 at 05:49
-
you can check file creation/modified time time, http://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python – user2109788 Jun 20 '14 at 06:20
-
For example, there's a apache log file /var/log/apache2/access.log. to keep this file in a reasonable size. after some time, this file will be renamed to access.log.0 or something. but I need to always print out new contents in /var/log/apache2/access.log – Daniel Dai Jun 20 '14 at 06:37
1 Answers
You are trying to defeat the purpose of log rotation if you are populating the same log file even after its rotated. One of the reason for doing log rotation is not to grow log size too much so that we don't have to face difficulties in opening\searching log information and your case is defeating this purpose. Still if you want to do that then you can check the folder where log files are kept after rotation and you can find out the latest rotated log file say that latest rotated log file name is application.log.x (where x is a number i.e.1,2,3,..) then before performing a write operation to log file you need to again check the log directory to check what is the latest rotated file and if there is a file later than application.log.x that means the log file in which you were writing is rotated and you can write the log to the logfile named as application.log.x+1.
On the other hand if log rotation is appending timestamp value in the logfile name to rename it then you need to check the latest rotated file before you open the log file for writing (say its app.log.timestamp ) and before writing again you need to check the log directory to find out the latest rotated log file if you find a rotated log file with greater time stamp than the time stamp of app.log.timestamp then you should use the file with name app.log.(timestamp + time duration for log rotation)
Note: Rotation happens mainly on two basis i.e. size or timestamp and usually in my observation a file is renamed after rotation by appending a number or timestamp in its name e.g. if log name is application.log then after location its name become application.log.x (where x is a number 1,2,3...) or application.log. where timestamp is the date time when log rotation happened

- 21
- 2
-
Yes. I understand that. What I need to do is tail -f filename.log can always print out the new contents, whether it's rotated or not. – Daniel Dai Jun 20 '14 at 06:41
-
oh yeah if you always want to use the latest log file then you can directly us tail command with logname (e.g. application.log) – code_explorer Jun 20 '14 at 06:55