I created a systemd service on my Pi 4 that writes std output to a file using StandardOutput=file:/file/location/file.log
. Is there a way to limit the file size of the log file to prevent it from taking up too much space?
1 Answer
I think the most forward way of dealing with this is using the logrotate
program (probably already installed, and automatically running periodically, e.g. once a day).
For that to work, you'd add a file yourservice.conf
in the /etc/logrotate.d
directory (check that /etc/logrotate.conf
contains include /etc/logrotate.d
). This makes a new file every (a little more than) 10 MB, and keeps the most recent 5:
/file/location/file.log {
rotate 5
size 10M
postrotate
systemctl restart yourservice.service
endscript
}
If the frequency of logrotate.timer
is too low (default: daily), i.e. if your program writes more than size
in a single day, you will have to modify the timer interval.
Note that you would be well-advised to not even start writing high-rate logs you don't need on a raspberry pi, if /file/location/file.log is on an SD card: These tend to wear off relatively quickly. Worn-out flash storage is the nr 1 reason for data loss and hardware-caused failure in RPis and similar SBCs.
append:
ortruncate:
, notfile:
.