如何使用 cron 添加时间戳来记录输出条目?

d.r*_*.v. 5 apache bash cron

我正在尝试安排 htcacheclean 使用 cron 每半小时运行一次。服务本身运行良好,但我不知道如何获取时间戳以附加到日志条目本身(而不是 cron-log 文件名)。

我无法在任何地方找到关于如何将时间戳添加到日志条目本身的答案。我只不断看到有关如何将日期时间戳添加到 cron 日志文件名的问题和答案,这不是我想要做的。

crontab -e这就是我现在所拥有的:

0,30  *   *   *   *       /usr/sbin/htcacheclean -v -n -t -p/var/cache/apache/mod_disk_cache -l1M >> /path/to/cron-output.log 2>&1
Run Code Online (Sandbox Code Playgroud)

目前,这就是我的输出打印方式:

Statistics:
size limit 1.0M
total size was 167.4K, total size now 167.4K
total entries was 5, total entries now 5
Run Code Online (Sandbox Code Playgroud)

现在我只需要一个时间戳出现在“统计”之前的日志条目旁边。

编辑:

我正在尝试做的示例:

0000-00-00 00:00:00: Statistics:
size limit 1.0M
total size was 167.4K, total size now 167.4K
total entries was 5, total entries now 5
Run Code Online (Sandbox Code Playgroud)

我想添加年、月、日、时、分、秒。

提前致谢!

解决方案:

我想按照@glenn jackman 的建议在这里添加完整的解决方案。

0,30  *  *  *  *    { printf "\%s: " "$(date "+\%F \%T")"; /usr/sbin/htcacheclean -v -n -t -p/var/cache/apache/mod_disk_cache -l1M ; } >> /path/to/cron-output.log 2>&1
Run Code Online (Sandbox Code Playgroud)

在 cron 任务中添加printf命令后,我的输出现在如下所示:

2018-02-05 21:10:01: Statistics:
size limit 1.0M
total size was 1009.0K, total size now 1009.0K
total entries was 24, total entries now 24
Run Code Online (Sandbox Code Playgroud)

gle*_*man 7

您可以date在 cron 条目中使用该命令,如下所示:

0,30 * * * * { printf "\%s: " "$(date "+\%F \%T")"; /usr/sbin/htcacheclean -v -n -t -p/var/cache/apache/mod_disk_cache -l1M ; } >> /path/to/cron-output.log 2>&1
# ...........^.^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.........................................................................^^^
Run Code Online (Sandbox Code Playgroud)

printf有点复杂,但它会像您想要的那样抑制换行符。

编辑以逃避百分号。请参阅下面的评论。