New log file every time cron job runs

北城余情 提交于 2019-12-10 17:28:14

问题


I have figured out how to output cron jobs to a log file using >> and providing a path to the log file. The >> appends log information to the existing file. How can I make it so the cron job creates a new log file every time it runs? (i.e. rsync.log, rsync(1).log, rsync(2).log -- ideally though I'd like the file name of the log to be something like DD-MM-YY.log).

I want a separate log file so this one log file doesn't get so huge and if/when we go to look if a file/folder was successfully backed up (I'm running an rsync command in the cron job) we don't have to comb through a MASSIVE log file.

Additionally, when the cron job is outputted to the log file, there are no time/date references. Example of my first log output:

**sending incremental file list**
**sent 78 bytes  received 11 bytes  35.60 bytes/sec**
**total size is 0  speedup is 0.00**

That's it. The timestamp on this logfile will keep changing every time the job is run, so we wouldn't even be able to tell what day that particular file/folder was copied via rsync. If I had a separate log file for every time the cron job ran, I could just open the log file for the particular date that it was created and view what was backed up.

My current cronjob:

*/1 * * * * rsync -avz /home/me/test/ 1234@xxx-a123.rsync.net:test/ >>/home/me/cron_logs/homedir_backups/rsync.log 2>&1

I only have it set to 1 minute for testing purposes. Eventually this will only run daily at midnight.


回答1:


If you want time stamped logs, you add the string of a formatted date command, date +%d%y%m for day month year in number format.

You can use backtick to put the string in the cron:

~$ /home/me/cron_log-`/bin/date +%d-%m-%y`

So the file name will have the current date appended to it. The backtick says "run this command and put the output here as a string".

Now the problem is that your directory might get huge and then you have to write a short script to delete them by time. I have a script that reads the format and keeps X and deletes the rest but most people would just use "find" to delete by time older stuff, like logs that have mtime > 1 year.



来源:https://stackoverflow.com/questions/26619961/new-log-file-every-time-cron-job-runs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!