【问题标题】:How to add timestamp to log output entries with cron?如何使用 cron 为日志输出条目添加时间戳?
【发布时间】:2018-07-15 17:17:11
【问题描述】:

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

目前我的输出是这样打印的:

Statistics:
size limit 1.0M
total size was 167.4K, total size now 167.4K
total entries was 5, total entries now 5

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

编辑:

我正在尝试做的示例:

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

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

提前谢谢!

解决方案:

我想按照@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

在 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

【问题讨论】:

标签: bash apache cron


【解决方案1】:

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

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
# ...........^.^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.........................................................................^^^

printf 有点复杂,但它会根据需要抑制换行符。

已编辑以转义百分号。请参阅下面的 cmets。

【讨论】:

  • 谢谢@glenn jackman,这行得通。我不得不通过在日期的 '%' 符号前面添加反斜杠来对其进行轻微修改,因为 cron 将在 { printf " 处停止执行。这对我有用:{ 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
  • 是的,我忘记了。这是 crontab 中经常犯的错误。
  • 是否可以使用 bashrc 函数,例如 { print_date();命令 } >> 日志文件?试图缩短 cron 作业。
【解决方案2】:

我正在使用这个。

#backup.sh
(date; /usr/bin/rsync -au  /sorcedir/ /dest/dir) &> /somedir/logfile.log

#crontab -e
*/30 */1 * * * /bin/bash /somedir/backup.sh

【讨论】:

    猜你喜欢
    • 2017-04-07
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 2020-08-18
    相关资源
    最近更新 更多