Home > linux > How do I make crontab generate a unique log each time it runs a job?

How do I make crontab generate a unique log each time it runs a job?

September 25Hits:1
Advertisement

Here is the crontab job

/usr/local/bin/python2.7 /home/scripts/script.py >> /home/scripts/logs/log.log 2>&1 

How do I generate a new log every time the job is run?

I am cool with adding an increasing counter to the log file each time it is generated. Do not know how to do this.

Do I really have to run another cron job to do that?

Thanks!

Answers

You can use the date command to generate a unique(ish) filename:

/usr/local/bin/python2.7 /home/scripts/script.py > /home/scripts/logs/"`date +\%d\%m\%y_\%H\%M\%S`".log 2>&1

EDIT: Make sure to escape the percentage signs (\%). They have a special meaning in cron and the crontab will return an error.

That way, a new log file (called <date_time>.log) will be created every time your job runs.

$ date; touch "`date +%d%m%y_%H%M%S`.log"
  Tue Sep 25 04:39:25 CEST 2012
$ ls *log
  250912_043925.log

Assuming your script does not run more often than once a second (which it can't if you are running a simple crontab), you should be fine.

If, as suggested in the comments, your script is run by different users, you can add the user name to the log file's name:

/usr/local/bin/python2.7 /home/scripts/script.py > /home/scripts/logs/$(echo -n `whoami`_`date +\%d\%m\%y_\%H\%M\%S`).log 2>&1

Tags:linux, crontab

Related Articles

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 1.018 s.