PHP Error Handling Logging Errors - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Error Handling Logging Errors - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Tuesday, July 2, 2019

PHP Error Handling Logging Errors

PHP Error Handling


Logging Errors

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.

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

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

The __FILE__ constant is the current filename, __LINE__ is the current line number, __FUNCTION__ is the current function name, __METHOD__ is the current method name (if any), and __CLASS__ is the current class name (if any). Starting with PHP 5.3.0, __DIR__ is the directory that __FILE__ is in and __NAMESPACE__ is the current namespace. Starting in PHP 5.4.0, __TRAIT__ is the current trait name (if any).

No comments:

Post a Comment

Post Top Ad