Question

I have a crontab setup to run a perl script every hour, at 5 minutes past the hour (so 2:05, 3:05, 10:05, etc.):

5 * * * * perl /abs/path/to/my/script.pl >> /abs/path/two/my/script-log.txt 2>&1

As you can see, it's also redirecting both STDOUT and STDERR to the same log file.

I've been asked to refactor either the Perl script, the crontab entry, or to add any new code/scripts necessary so that every night, at midnight, the script-log.txt gets cleared/flushed/emptied.

That is, every night, at midnight, if script-log.txt has 20MB of text in it, to clean it out so that it now has nothing (0bytes) in it, and then at 12:05 AM the crontab would kick back in, run script.pl, and start adding more text to the same script-log.txt log file.

It would be enormously easier if there was a way to modify the crontab entry with some Linux/Perl magic to set up such a "daily rolling log file". In a worst-case scenario, we can always write a new script to purge script-log.txt and cron it to run at midnight. But my higher-ups would greatly prefer to not have yet-another cron job, and are looking for a way to do this from the entry itself (if possible).

In reality, we have dozens of entries that work like this, and so the problem with writing "purging script" and cronning it to run at midnight is that we'll constantly be updating the purging script as we add/delete other scripts that generate these kinds of log files. Thus, if we can set such purging up at the entry level, each cron entry cleans itself. Thanks for any insight/pointers/suggestions in advance.

Was it helpful?

Solution

You might want to look into logrotate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top