Recipe 20.9. Logging Errors

20.9.1. Problem

You want to save 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.

20.9.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)); }

20.9.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__, __LINE__, __FUNCTION__, __CLASS__, and __METHOD__ "magic" constants in your error messages:

error_log('['.__FILE__.']['.__LINE__."]: $error");

The __FILE__ constant is the current filename, and __LINE__ is the current line number.

The __FUNCTION__ constant was added in PHP 4.3.0. From that PHP version through the rest of the PHP 4.x series, the __FUNCTION__ constant returns the current function name in lowercase; beginning in PHP 5, the constant returns the function name as it was declared. The __CLASS__ constant, which returns the current class name, was also introduced in PHP 4.3.0. __CLASS__ behaves exactly the same way as __FUNCTION__ in regard to case sensitivity in PHP 4.x and PHP 5.

PHP 5.0.0 introduced the __METHOD__ constant, which returns the current class method name. The method name returned is case sensitive to how it was declared.

20.9.4. See Also

Recipe 20.6 for hiding error messages from users; documentation on error_log( ) at; documentation on "magic" constants at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: