Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running a php script via cron, how can I log any output?

Tags:

php

logging

cron

Morning all,

I have a php script which I have been testing, and seems to run fine when I call it from the command line.

I now want to automate it via cron, how can I get the outputs I have put into the file as checkpoints into a log file?

eg I have some simple echo commands in the script and I'd like the output to appear inside an existing log file (so that it get's automatically rotated etc)

thanks,

Greg

like image 522
kitenski Avatar asked Jun 18 '10 12:06

kitenski


2 Answers

Cron command to run:

/path/to/php -f /path/to/script.php >> /path/to/logfile.txt
like image 124
Your Common Sense Avatar answered Oct 10 '22 20:10

Your Common Sense


Try something like this:

<?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);
}
?>
like image 36
ChuckO Avatar answered Oct 10 '22 21:10

ChuckO