Rotate a Log File by Size

Hard ⏱ 18 min 31% acceptance ★★★★★ 4.9
Write append_with_rotation(path, line, max_bytes) that appends line (plus newline) to the log — but first, if the file exists and its size already exceeds max_bytes, renames it to path + '.1' (replacing any previous .1) so the fresh write starts a new file.

Examples

Example 1
Input
append_with_rotation('app.log', 'boot', 1024)
Output
app.log gains 'boot'; if it was >1024 bytes it moved to app.log.1 first
Explanation

Single-generation size-based rotation.

Constraints

  • Use os.path.getsize and os.replace.
  • Rotation happens before the write.

Topics

File Handlingos modulerotation

Companies

AmazonDatadogSplunk

Hints

Hint 1

os.replace overwrites the destination atomically.

Hint 2

Check existence before calling getsize.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.