Yes, there's a proper way: You don't clear logs at all. You rotate them. Rotation involves switching log output to a new file, under the same name, with the previous N log files kept under a set of N related filenames.
How one rotates logs depends from how one is writing them in the first place. This is an oft-overlooked point. Some of the answers here touch upon it at least, mentioning that some logging programs keep an open file descriptor for the log file, so just deleting the file won't free up the space, or indeed even switch output to a fresh log file.
If the program writing the log file is multilog
from the daemontools
package, for example, then you don't do anything to rotate the logs at all — no manual scripts, no cron
jobs. Simply tell multilog
that log output is to a directory, and it will itself maintain an automatically rotated and size-capped set of N log files in that directory.
If the program writing the log files is svlogd
from the runit
package, for another example, then much the same applies. You don't do anything at all apart from point the tool at a directory. It will itself maintain an automatically rotated and size-capped set of N log files in that directory.
If you are using rsyslog
to write log files, then the logging program can be told to stop after the log file reaches a certain size and run a script. You have to write the meat of the script, to actually rename the log file and delete old log files based upon total size constraints, but at least the logging program has closed the file and paused log writing whilst this is happening.
The old syslogd
way of rotating logs, still expected by logging programs such as syslog-ng and as exemplified by tools such as logrotate
mentioned by djangofan
in another answer here, is somewhat more haphazard. One runs a cron
job that periodically renames the log files, and restarts the logging daemon (using whatever daemon supervisor it is running under). The problem with this, of course is that it doesn't enforce an overall size cap. On slow weeks one can get N very small daily log files, whereas on busy days one can get 1 very big log file that's well over the size limit.
This is why later and better tools like multilog
and svlogd
have file size configuration options and actually check the log file sizes themselves, of course. The world has learned that polling the logs on a schedule with cron
jobs, or even a logrotate
daemon, leaves windows for the size to be wrong, and that the proper place to have these checks, and so rigourously enforce administrator-defined size caps so that one's log files don't ever swallow the partition that they are on, is in the program that is actually writing the files out in the first place.