While error_log provides a straightforward way to log errors, it lacks flexibility and can lead to maintenance challenges if the log file path needs to be changed across multiple files or classes.
To overcome these limitations, consider using trigger_error to raise errors and set_error_handler to log them. trigger_error allows you to generate standard PHP errors, while set_error_handler provides a custom callback to handle the error logging. This approach:
<code class="php">// Define the error handler function function errorHandler($errno, $errstr, $errfile, $errline, $errcontext) { // Perform error handling actions, such as logging errors } // Set the custom error handler set_error_handler('errorHandler');</code>
Similar to error handling, use set_exception_handler to define a callback function for handling exceptions. Exceptions can be handled in various ways:
Errors
<code class="php">// Raise an E_USER_NOTICE error trigger_error('Disk space is low.', E_USER_NOTICE); // Raise an E_USER_ERROR fatal error trigger_error('Cannot continue due to fatal error.', E_USER_ERROR);</code>
Exceptions
Catch and Fix:
<code class="php">try { // Code that may throw an exception } catch (Exception $e) { // Resolve the exception and continue }</code>
Append and Re-Throw:
<code class="php">try { // Code that may throw an exception } catch (Exception $e) { // Add context and re-throw throw new Exception('Additional context: ' . $context, 0, $e); }</code>
The above is the detailed content of How to Achieve Seamless Error Logging in PHP?. For more information, please follow other related articles on the PHP Chinese website!