App patterns · real, tested code

Rotate and Archive Log Files in Larzscript

Once a log file crosses a size threshold, shift it into numbered backups and start a fresh one - the same scheme logrotate uses.

No dedicated package for this - just file_exists()/read_file()/rename()/write_file(), the same OS-facing builtins every other file-handling task in this cookbook uses.

Code

fn rotate_log(path, max_bytes, keep) {
  if not file_exists(path) { return false }
  let size = len(read_file(path))
  if size < max_bytes { return false }
  let i = keep
  while i >= 1 {
    let src = i == 1 ? path : path + "." + str(i - 1)
    let dst = path + "." + str(i)
    if file_exists(src) { rename(src, dst) }
    i = i - 1
  }
  write_file(path, "")
  return true
}

write_file("/tmp/app.log", "line one\nline two\n")
print(rotate_log("/tmp/app.log", 5, 3))
print(sorted(filter(fn(f) { return f.starts_with("app.log") }, listdir("/tmp"))))
print(read_file("/tmp/app.log.1"))
Output
true
[app.log, app.log.1]
line one
line two