【问题标题】:running a php script via cron, how can I log any output?通过 cron 运行 php 脚本,如何记录任何输出?
【发布时间】:2010-06-18 12:41:13
【问题描述】:

早上好,

我有一个我一直在测试的 php 脚本,当我从命令行调用它时似乎运行良好。

我现在想通过 cron 将其自动化,如何将我作为检查点放入文件中的输出放入日志文件中?

例如,我在脚本中有一些简单的回显命令,我希望输出出现在现有日志文件中(以便自动旋转等)

谢谢,

格雷格

【问题讨论】:

  • 基于 UNIX 的 crons 会将作业的输出通过电子邮件发送给正在运行作业的 ID 的用户。因此,如果您不想像其他答案中建议的那样弄乱输出重定向,您可以查看那些自动电子邮件。

标签: php logging cron


【解决方案1】:

要运行的 Cron 命令:

/path/to/php -f /path/to/script.php >> /path/to/logfile.txt

【讨论】:

  • >> 追加到日志文件。
  • 谢谢 - 如果我使用 /var/log/cron 作为日志文件,可以吗?这样它将自动存档,修剪等
【解决方案2】:

试试这样的:

<?php
function logToFile($filename, $msg)
{ 
    $fd = fopen($filename, "a");
    $str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
    fwrite($fd, $str . "\n");
    fclose($fd);
}

function logToMail($msg, $address)
{ 
    $str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;   
    mail($address, "Log message", $str);
}

function logToDB($msg, $type)
{ 
    // open connection to database
    $connection = mysql_connect("localhost", "joe", "pass") or die ("Unable to connect!");
    mysql_select_db("logdb") or die ("Unable to select database!");

    // formulate and execute query
    $query = "INSERT INTO log (date, type, msg) VALUES(NOW(), '$type', '$msg')";
    mysql_query($query) or die ("Error in query: $query. " .mysql_error());

    // close connection
    mysql_close($connection);
}
?>

【讨论】:

  • 这里的问题是,如果 php 脚本由于某种原因失败,则日志记录方法可能永远不会被执行。上面接受的答案会将任何脚本输出发送到日志文件。
猜你喜欢
  • 2019-07-23
  • 2016-10-01
  • 2016-04-14
  • 2012-08-09
  • 1970-01-01
  • 2020-02-28
  • 1970-01-01
  • 2018-03-22
  • 2014-10-21
相关资源
最近更新 更多