title besides title

 

Saturday, December 1, 2012

PHP : Web Basics - [8.18] Logging Errors

8.18.1 Problem

You want to write program errors to a log. These errors can include everything from parser errors and files not being found to bad database queries and dropped connections.

8.18.2 Solution

Use error_log( ) to write to the error log:
// LDAP error
if (ldap_errno($ldap)) {
    error_log("LDAP Error #" . ldap_errno($ldap) . ": " . ldap_error($ldap));
}

8.18.3 Discussion

Logging errors facilitates debugging. Smart error logging makes it easier to fix bugs. Always log information about what caused the error:
$r = mysql_query($sql);
if (! $r) {
    $error = mysql_error( );
    error_log('[DB: query @'.$_SERVER['REQUEST_URI']."][$sql]: $error");
} else {
    // process results
}
You're not getting all the debugging help you could be if you simply log that an error occurred without any supporting information:
$r = mysql_query($sql);
if (! $r) {
    error_log("bad query");
} else {
    // process result
}
Another useful technique is to include the _ _FILE_ _ and _ _LINE_ _ constants in your error messages:
error_log('['._ _FILE_ _.']['._ _LINE_ _."]: $error");
The _ _FILE_ _ constant is the current filename, and _ _LINE_ _ is the current line number.