Let me be clear up front: logrotate exists, it is installed on every
system I own, and it works. This project was an excuse to write some Go on
a Sunday and end up with a tool shaped exactly like my lab. It rotates log
files for the handful of services I run from plain binaries instead of
containers: when a log passes a size threshold, it gets renamed with a
timestamp, gzipped, and anything older than the retention limit is
deleted.
The interesting 40 lines
The core of it is small enough to hold in your head:
func rotate(path string, keep int) error {
stamp := time.Now().Format("2006-01-02-150405")
dst := path + "." + stamp
if err := os.Rename(path, dst); err != nil {
return err
}
if err := gzipFile(dst); err != nil {
return err
}
return prune(path, keep)
}
The one subtlety: the running service has to reopen its log file after the
rename, or it will happily keep writing to the renamed file forever. My
services get a SIGHUP after rotation; the two that couldn’t handle that
got taught, which was a useful afternoon in itself.
Why bother
Three reasons, in ascending order of honesty. It has no configuration file
- the conventions of my lab are compiled in, so there is nothing to drift.
It was a good way to learn Go’s
compress/gzipand signal handling on a problem small enough to finish. And there is a particular pleasure in a tool that does one thing for an audience of one.
The full source is about 200 lines. It has run every night since March without a single complaint, which is more than I can say for some software with entire teams behind it.