8.17. Logging Errors
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.
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));
}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.
See Also
Recipe 8.15 for hiding error messages from
users; documentation on error_log( ) at
http://www.php.net/error-log.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access