PHP Error Logging
When testing a new website there are always going to be bugs. As much as we test our programs within our own department, the client will inevitably find bugs. One thing we can do to help solve these situations when they arise is to create an error log.
PHP when installed creates it’s own error log. However, if you are on a shared hosting plan or want to see errors only for a specific site, it makes sense to customize how PHP handles those errors.
The first thing we need to do is setup the function that is going to handle the errors. We will call this myError. This function will take in 4 arguments.
- $errorno – the error number
- $errstr – the text describing the error
- $errfile – the file in which the error occurred
- $errline – the line in which the error occurred
Our function will look like this:
define("LOG_FILE", "/website/path/errorfile.log"); function myError($errno, $errstr, $errfile, $errline) { switch ($errno) { case E_ERROR: case E_WARNING: case E_NOTICE: $message = "Error Number: $errno - Error string: $errstr"; error_log (strftime ("%D %T") . " | " . $errfile . " | " . $errline . "n" . $message . "nn", 3, LOG_FILE); break; } }
What we’ve added in there now is the case statement. Basically this specifies what specific errors we want to track. There are a lot of small error types that we don’t need to track. The define statement above defines our constant for the log file location.
Next we need to tell PHP to use this function every time there is an error. We use the set_error_handler function.
set_error_handler('myError');
Notice that the text “myError” is in quotes without the brackets that normally identify a function. This statement would usually be put in an include file that gets executed before each page. Obviously, if we set the error handler after an error happens, it will not be logged.
Of course, this is a very basic error log and won’t always give you all the information you need. You could perhaps add a backtrace to give more information about the error. Implementing our own simple error handler can help us capture those last few remaining bugs which will hopefully prevent any from seeing the light of day or the client.
