Home >Database >Mysql Tutorial >How can I log PHP errors to a MySQL database instead of the error_log file?

How can I log PHP errors to a MySQL database instead of the error_log file?

DDD
DDDOriginal
2024-11-06 06:35:021000browse

How can I log PHP errors to a MySQL database instead of the error_log file?

Outputting PHP Errors to a Database Without Modifying Error_Log

By default, PHP errors are logged to the standard error_log file. To direct these errors to a MySQL database instead, consider employing a custom error handler.

To implement this solution, create a custom error handler function that processes error details and writes them to the database. For instance:

function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    // Establish a database connection or utilize an existing one
    
    // Prepare and execute an SQL query to insert the error details
    mysql_query("INSERT INTO error_log (number, string, file, line) ".
                 "VALUES .....");         
    
    // Prevent execution of the default PHP error handler
    return true;
}

Following this, you can set the user-defined error handler as the global error handler:

// Disable the default error handler
$old_error_handler = set_error_handler("myErrorHandler");

With this custom error handler in place, all PHP errors will be directed to the designated MySQL database instead of the error_log file.

The above is the detailed content of How can I log PHP errors to a MySQL database instead of the error_log file?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn