Current Location: Home> Latest Articles> Integrate mysqli::debug in automated scripts for periodic log collection

Integrate mysqli::debug in automated scripts for periodic log collection

M66 2025-06-01

In PHP development, mysqli::debug() is a debugging tool that is overlooked by many developers but is of great value. It allows you to log debug logs for MySQLi extensions and is of great significance for analyzing database connections, query execution, and performance bottlenecks. This article will explore in-depth how to integrate mysqli::debug() in automated scripts, realize regular log collection, and improve overall debugging efficiency.

1. Introduction to mysqli::debug()

mysqli::debug() is a static method in the MySQLi extension to enable client debug logging. It is used as follows:

 mysqli::debug("d:t:o,/tmp/client.trace");

The meaning of this command is:

  • d : Print debugging information

  • t : Add a timestamp

  • o,/tmp/client.trace : Writes the output to the specified log file

But be aware: mysqli::debug() must be called before establishing a database connection, otherwise it will not take effect.

2. Why use mysqli::debug in automated scripts?

In automated tasks (such as timed data synchronization, batch data processing, etc.), it is often necessary to track the behavior of the database during script operation. Integration of mysqli::debug() can bring the following advantages:

  • Problem backtracking : When data synchronization fails or an exception occurs, the problem can be quickly located through the log.

  • Performance optimization : analyzes the time-consuming and assists in optimization.

  • Improve debugging efficiency : discover potential connection or query problems faster.

3. Integration ideas and implementation examples

Here is a simple automation script example showing how to integrate mysqli::debug() :

 <?php
// Enable MySQLi Debug log,Log file paths are recommended to be rotated or cleaned regularly
mysqli::debug("d:t:o,/var/log/mysqli_debug.log");

// Database connection configuration
$host = 'localhost';
$user = 'your_user';
$password = 'your_password';
$database = 'your_database';

// Create a connection
$mysqli = new mysqli($host, $user, $password, $database);

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

// Simulate a database operation
$query = "SELECT * FROM users WHERE status = 'active'";
$result = $mysqli->query($query);

if ($result) {
    while ($row = $result->fetch_assoc()) {
        // Here you can perform the processing logic you need
        echo "user:" . $row['username'] . "\n";
    }
    $result->free();
} else {
    error_log("Query failed: " . $mysqli->error);
}

$mysqli->close();
?>

4. Cooperate with timed tasks to realize log rotation

To achieve regular log collection , it is recommended to combine cron or scheduled tasks of the operating system:

 # Clean old logs and restart log collection every morning
0 0 * * * rm -f /var/log/mysqli_debug.log

Logrotate can also be used to implement log rotation and retention policies.

5. Remote log upload (optional)

In a distributed environment, logs can also be uploaded regularly to remote servers, for example:

 $logFile = '/var/log/mysqli_debug.log';
$remote = 'https://m66.net/api/upload_log';

if (file_exists($logFile)) {
    $logData = file_get_contents($logFile);
    $response = file_get_contents($remote . '?token=YOUR_TOKEN', false, stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => "Content-type: application/x-www-form-urlencoded",
            'content' => http_build_query(['log' => $logData])
        ]
    ]));
}

6. Things to note

  • mysqli::debug() may be disabled in some production environments, and support needs to be verified before deployment.

  • Please make sure that the log file path has writable permissions to avoid debugging failures due to permission issues.

  • Log content may contain sensitive information, and it is recommended to encrypt transmission or restricted access.

7. Summary

By integrating mysqli::debug() in automated scripts, we can obtain clearer database behavior records and improve debugging efficiency, especially when dealing with large batches of data or troubleshooting occasional problems. Combining timed tasks and log rotation strategies to maximize the effectiveness of this tool is a trick that every PHP developer who focuses on maintainability and efficiency cannot ignore.