Logging ALL stderr output of crontab to file

Mas*_*ton 13 cron logs io-redirection

For example, I can log stderr of one script in this way:

* * * * * run_script.sh > /var/log.txt 2>&1
Run Code Online (Sandbox Code Playgroud)

But I want to log stderr of all scripts in my crontab. I can append > /var/log.txt 2>&1 to all scripts, but it's not good if I have hundreds of scripts in cron. Is there another, more simple way to do this?

Kyl*_*nes 6

In crontab, you can set MAILTO to point to a mail alias that runs a script. That script would accept a mail message, strip off the headers and other goop, and log the remainder with logger. Since all cron script output is sent to the address specified by MAILTO, you'd capture everything.

示例:在 crontab 中

MAILTO=myalias
Run Code Online (Sandbox Code Playgroud)

在 /etc/mail/aliases 中(假设您使用的是 sendmail)

myalias:"|/usr/local/bin/my-processing-script.sh"
Run Code Online (Sandbox Code Playgroud)

并让脚本去掉邮件头并处理 cron 输出。


Aki*_*Aki 5

命令产生的任何输出都会发送给在 crontab(5) 文件中设置的 MAILTO 环境变量中指定的用户,或者,如果未设置 MAILTO 变量(或者如果这是 at(1) 或 batch(1) 作业),发给作业的所有者。如果命令不产生输出或 MAILTO 环境变量设置为空字符串,则不会发送邮件。

因为它使用本地邮件,所以你真的不需要设置任何东西,或者如果它还没有安装 mailx 就可以了。Cron 将向您发送输出,您可以将邮件保存在一个文件中并从那里做很多事情。尝试修改 cron 的工作方式以直接满足您的需要并不是要走的路。如果您不这么认为,只需修补并重新构建 cron,将其命名为 my_cron 并使用它代替 cron。并准备好最终使您的 my_cron 保持最新并经常重新构建它。

在所有脚本的开头添加它以记录所有内容并在第一个错误处停止

exec 2>&1 > /var/log/YOUR_LOG_FILE
set -e
Run Code Online (Sandbox Code Playgroud)

  • 这是非常疯狂的,在一个最小的服务器上,您需要安装邮件服务,可能还需要安装邮件客户端,只是为了读取 Cron 产生的错误。这感觉像是一个无政府主义的设计决定。 (2认同)