Logging Errors
Logging erros normally includes shielding the website visitors from the full effects of the error, while giving yourself as much information as possible about the problem so you can set about fixing it in a timely manner.
Error logging in PHP is a very helpful tool which can be use to record messages about errors that have occured in your website. This way, you don’t have to rely on your site visitors notifying you when things go wrong.
error_log()
Let’s modify our custom error handler function from the previous section to use a useful function of PHP, error_log() , normally this function usually takes three variables, and a fourth when we are sending error logs via email.
- Error message : The message to send to the log
- Message type :
- 0 - Use PHP’s system logger to record the message
- 1 - Send the message via email to the address specified in the next argument 3 -Write the error to the file specified in the next argument
- Message destination : When message type is set to 1 or 3, this is either the email address, or the local file to be written to.
- Custom headers : When message type is set to 1 (send via email) this variable holds the custom mail headers used by mail() - see the tutorial on PHP and email
Code:
function customError($level, $message, $file, $line)
{
//here we'll append the error to the local file error.log
error_log("Error level $level occured : '$message'",3, "error.log");
//now that we've safely recorded the error, we don't need to rely on the visitor
//to inform us of any faults
}
set_error_handler("customError");
//let's trigger the error again...
echo($hello_world);
Now, we won’t see anything appear on screen, but the error will be recorded within the error.log file. Here, if we look on the first line of that file, we will see
Code:
Error level 8 occured : 'Undefined variable: welcome_world'
Selective error handling
With this we can modify the behaviour of our custom error handler to deal with the errors more effectively
Code:
function customError($level, $message, $file, $line)
{
if($level >= E_USER_ERROR)
error_log("Error level $level occured : '$message'",3, "error.log");
}
Now, this function will ignore all errors less serious than E_USER_ERROR and log only those errors which pose a risk to the application. We can test this by use of the trigger_error() function, which will generate a user-triggered error.
Code:
trigger_error("User generated error");
It will cause the following line to appear in error.log
Code:
Error level 1024 occured : 'User generated error'
Fatal errors : Unfortunately, PHP doesn’t allow fatal errors to be handled with custom error handlers - the assumption here being that a fatal error will pretty much have killed your script anyway, with no hope of recovery. Fatal errors can be created by calling functions that don’t exist, for example
Bookmarks