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
Related
Retry with Exponential Backoff in LarzscriptRetry a flaky call a few times, waiting longer between each attempt, instead of failing on the first hiccup or hammering a struggling service.→Memoize a Function in LarzscriptCache a function's results so calling it twice with the same input only does the real work once.→Implement a State Machine in LarzscriptDeclare states and transitions, fire events, and let the machine reject anything that isn't a legal move - a document workflow (draft -> review -> published) in a few lines.→Paginate a List in LarzscriptSlice a list into pages with the has_next/has_prev/1-based-index bookkeeping every list-showing page needs, without hand-rolling the off-by-one math again.→