question 190 Files & Directories · hard
Rotate a log file
A log that only ever grows becomes impossible to open. Write a function that rotates it: the newest lines stay in the log, and older lines move to an archive file next to it.
Function
rotate_log(path, keep)Whenthe log has more than
keep lines; otherwise nothing changes and no archive is createdArchivethe older lines are added, in order, to the end of
path + ".1" (created if missing, never emptied)Logafterwards holds only its last
keep lines, each ending with \n; keep may be 0Returnshow many lines were moved to the archive
Examples
callrotate_log('app.log', 2)returns3
callrotate_log('short.log', 5)returns0