2

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?

4
  • I don't think there is in this constellation. What would you like to happen when the maximum size is reached? Service gets killed? New file gets started, and old file renamed, old-old files get deleted? Commented Jan 10, 2023 at 16:23
  • @MarcusMüller Best case, I would like the oldest logs to be removed and the newest ones added to the log file. At the very minimum I would like the service to stop writing to that file.
    – SudoObey
    Commented Jan 10, 2023 at 16:28
  • ah removing the beginning of a file is not something you can "easily" implement on a UNIXoid system (or in fact, any system I'm aware of), that would always require a complete re-writing of the file. What you could do is use logrotate! Commented Jan 10, 2023 at 16:31
  • btw, almost certain you either want append: or truncate:, not file:. Commented Jan 10, 2023 at 16:33

1 Answer 1

4

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.

1
  • The best way is to stop the service in prerotate and start it after postrotate
    – SuB
    Commented May 7 at 12:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .