77

I have a crontab like this on a LAMP setup:

0 0 * * * /some/path/to/a/file.php > $HOME/cron.log 2>&1 

This writes the output of the file to cron.log. However, when it runs again, it overwrites whatever was previously in the file.

How can I get cron to output to a file with a timestamp in its filename?

An example filename would be something like this: 2010-02-26-000000-cron.log

I don't really care about the format, as long as it has a timestamp of some kind.

1
  • 10
    if you don't want $HOME/cron.log to be overwritten, use >> not > Commented Feb 27, 2010 at 8:01

6 Answers 6

131

Try:

0 0 * * * /some/path/to/a/file.php > $HOME/`date +\%Y\%m\%d\%H\%M\%S`-cron.log 2>&1 

Play around with the date format, if you like; just be sure to escape any % like \%, as above.

5
  • 2
    And let me generally suggest an approach to file names like 0 0 * * * /some/path/to/a/file.php > $HOME/scriptname-date +\%Y\%m\%d\%H\%M\%S.log Commented Oct 17, 2015 at 11:14
  • 1
    If you need it a little more human readable try: date +\%Y\ \%m\ \%d\ \%H:\%M:\%S-cron.log Commented Apr 4, 2016 at 13:35
  • 10
    @DevilCode, yes, although spaces in filenames aren't very conventional in Unix. Hyphens or underscores might be a better option: date +\%Y-\%m-\%d_\%H:\%M:\%S-cron.log. Commented Apr 4, 2016 at 23:47
  • 4
    Those freaking escape characters always get me. Thanks for the reminder! Commented Oct 8, 2019 at 0:21
  • 2
    This Note saved my life. "Play around with the date format, if you like; just be sure to escape any % like \%, as above." Commented Jul 14, 2022 at 10:18
24

I would highly recommend that you save everything into the same file, using timestamp, as explained on Abdullah Diab’s Blog.

remove

2>&1

... and run it through the timestamping script before saving it to log file.

timestamp.sh script:

#!/bin/bash while read x; do echo -n `date +%d/%m/%Y\ %H:%M:%S`; echo -n " "; echo $x; done 

Remember to chmod +x timestamp.sh to make it executable.

Then edit the cron job line using crontab -e to be like this:

/path/to/my/command.sh 2>&1 | /path/to/timestap.sh >> /var/log/cron/my_log.log 
0
7

You can also append your output to the log file by doing it like this:

0 0 * * * /some/path/to/a/file.php >> $HOME/cron.log 2>&1 
2

I modified the script like this:

`/bin/date +\%Y\%m\%d`.log 
-1

I solved this problem; just add the date path (/bin/date) before the date command.

1
  • 2
    Please add more info and example. Commented Jan 15, 2016 at 13:10
-1
@daily /some/path/to/a/file.php 2>&1 > $HOME/$(date +\%Y\%m\%d\%H\%M\%S)-cron.log 
1
  • 8
    This would need a lot of explanation. Commented Feb 22, 2019 at 17:22

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.