Want to log script activity in your Web application, but haveno clue where to begin? Take our handy tour of PHP's logging functions,and find out how simple it really is.
While the most common destination for log data is a text file, it's quite possible that you might want to send your log messages elsewhere as well. A frequently-used alternative to a text file, especially when the number of writes isn't too high, is an SQL database, where log messages are appended as records to the end of a table.
In order to illustrate this, consider the following example of an SQL table used to store log messages:
CREATE TABLE `log`
(
`date` TIMESTAMP NOT NULL,
`type` TINYINT NOT NULL,
`msg` VARCHAR(255) NOT NULL
);
And here's the rewritten logToDB() function, this time built
around PHP's MySQL database functions and the table above:
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);
}
$a = array("chocolate", "strawberry", "peach");
if (!in_array('fish', $a)) { logToDB("No fish available", 14); }
If you don't estimate seeing a very large number of writes,
using a database to store logs can offer significant advantages over a regular file, purely from the point of view of easier retrieval and sorting. Storing log messages in this manner makes it possible to easily retrieve ordered subsets of the log data, either by date or message type.
Another option might be to send log messages to a specified email address via PHP's mail() function - for example, alerting a sysop whenever a script encounters errors. Here's an example:
function logToMail($msg, $address)
{
// append date/time to message
$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
mail($address, "Log message", $str);
}
$conn = @mysql_connect("localhost", "joe", "pass");
if (!$conn) { logToMail("Could not connect to database",
"webmaster@my.domain.name.com"); }