Current Location: Home> Latest Articles> Integrate $errno with log system for error classification

Integrate $errno with log system for error classification

M66 2025-05-28

When developing PHP applications, mysqli extensions are a common way to interact with MySQL databases. When a database operation error occurs, the error code is usually obtained through mysqli::$errno and the error information is obtained in combination with mysqli::$error . However, how to effectively classify, analyze and record these error information into the log is an important step to improve application reliability.

This article will explain how to classify and record MySQL errors through PHP's mysqli::$errno and logging system. This can better track and handle database connection problems, query failures and other errors, making it easier to troubleshoot and repair later.

1. Catch mysqli errors

First, we need to know how to get error information through mysqli . The mysqli class provides several properties to help us catch database-related errors:

  • mysqli::$errno : Returns the error code of the previous MySQL operation.

  • mysqli::$error : Returns the error message of the previous MySQL operation.

Using this information, we can check whether each database operation is successful. If it fails, we can use this information to obtain a detailed error description.

 <?php
$mysqli = new mysqli("localhost", "user", "password", "database");

// Check the connection
if ($mysqli->connect_error) {
    echo "Connection failed: " . $mysqli->connect_error;
    exit();
}

// Execute a SQL Query
$result = $mysqli->query("SELECT * FROM non_existent_table");

if (!$result) {
    // Capture error codes and error messages
    $errno = $mysqli->errno;
    $error = $mysqli->error;
    echo "MySQL Error number: $errno, error message: $error";
}
?>

If the query execution fails, we can use mysqli::$errno and mysqli::$error to capture the error information and record it.

2. Integrate logging system

Next, we integrate these error messages into the log system. It is common practice to output error information to a log file, or use existing log libraries such as Monolog to implement more complex logging functions.

2.1 Using PHP built-in logging function

The easiest way is to use PHP's built-in logging function error_log() to log error.

 <?php
// Configure log file path
$log_file = "/path/to/your/logfile.log";

// 捕获error message并写入日志
if (!$result) {
    $errno = $mysqli->errno;
    $error = $mysqli->error;
    $log_message = date("Y-m-d H:i:s") . " - Error number: $errno, error message: $error\n";
    error_log($log_message, 3, $log_file);
}
?>

2.2 Logging with Monolog

For more flexible logging, we can use Monolog as a third-party library. Monolog supports a variety of log processors, which can output logs to files, databases, emails and other channels, and supports log levels (such as DEBUG , INFO , ERROR , etc.).

 <?php
require 'vendor/autoload.php';

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Create a log channel
$log = new Logger('my_logger');
$log->pushHandler(new StreamHandler('/path/to/your/logfile.log', Logger::ERROR));

// 执行Query并捕获mistake
if (!$result) {
    $errno = $mysqli->errno;
    $error = $mysqli->error;
    // 记录error message到日志
    $log->error("MySQL Error number: $errno, error message: $error");
}
?>

2.3 Error classification

Through logs, we can not only record error information, but also classify them according to different types of errors. For example, database connection failures, SQL query syntax errors, data constraint violations, etc. These errors can be recorded separately for later analysis.

We can define different log levels for different types of errors:

 <?php
if ($mysqli->connect_error) {
    $log->critical("数据库Connection failed: " . $mysqli->connect_error);
} elseif (!$result) {
    $errno = $mysqli->errno;
    $error = $mysqli->error;
    if ($errno == 1146) {
        $log->warning("There is no error in the table: $error");
    } else {
        $log->error("other MySQL mistake: $error");
    }
}
?>

In this example, if the database connection fails, we use the critical level to log the log, indicating a serious error. For errors that do not exist in the table, we use warning level records.

3. Analysis and monitoring

With the error logs, we can also analyze these logs to find potential problems in the application. For example, we can use the grep command to find specific errors in the log file, or use some log analysis tools to do more in-depth analysis.

If you want to automatically monitor database errors, you can combine some system monitoring tools (such as ELK Stack, Graylog, etc.) to detect and respond to database errors through log aggregation and analysis.

4. Summary

By integrating mysqli::$errno with the log system, we can better manage and monitor errors in MySQL database operations. This not only helps us catch and classify errors, but also facilitates later error analysis and debugging, thereby improving the reliability and stability of the application.

If you have used a log library like Monolog in your project, combined with mysqli error information, you can achieve more efficient error tracking and processing. Classifying and analyzing errors is also an important step in optimizing the system, helping developers discover potential problems early.