brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: copytruncate rotates a log for programs that never let go of the file

Linux
~/tips/tip-logrotate-copytruncate

rotate 4

Rotate the log of a program that keeps its log file open and can't reopen it.

Normal rotation renames app.log to app.log.1 and expects the program to start a fresh file. Plenty of programs don’t. They keep the old file open and go on writing into app.log.1, while the new app.log stays empty.

The copytruncate option in logrotate is made for them. It copies the log to the rotated name and then truncates the original to zero bytes in place, so the program keeps its open file and carries on writing into it.

/var/log/myapp/*.log {
    weekly
    rotate 4
    compress
    missingok
    copytruncate
}

Save that as /etc/logrotate.d/myapp and the regular logrotate run picks it up. I’d reach for this when a script or a small daemon writes its own log file and has no way to reopen it. When a program can reopen its log on a signal or a reload, a postrotate script that triggers that is the cleaner route.

The caveat is right there in the man page: between the copy and the truncate there’s a very small window, and anything written in that moment is lost. For a hobby service I can live with that, for logs you need as evidence later I wouldn’t. Also, a create line does nothing together with copytruncate, because the original file never goes away.

Further reading: logrotate(8) man page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link