Every SQL query in a MySQL database consumes a certain amount of time. To identify and locate performance bottlenecks, it is necessary to find the SQL statements that take longer to execute. MySQL’s slow query log feature records all SQL statements that exceed a specified execution time threshold.
By analyzing the slow logs, database administrators and developers can pinpoint slow queries and their execution times, enabling targeted performance optimization.
Edit the MySQL configuration file my.cnf to enable the slow query log by adding the following parameters:
slow_query_log = 1 # Enable slow query log slow_query_log_file = /var/log/mysql/mysql-slow.log log_queries_not_using_indexes = 1 # Log queries that do not use indexes
Parameter explanations:
After modifying the configuration file, restart MySQL to apply the changes:
service mysql restart
After restarting, you can monitor the slow query log in real-time with:
cd /var/log/mysql/ tail -f mysql-slow.log
Add or update the following parameters in the php.ini file to enable PHP slow logging:
slowlog = /var/log/php/php-slow.log request_slowlog_timeout = 10 # Timeout in seconds; requests longer than this will be logged
Parameter explanations:
After updating the configuration, restart the PHP service:
sudo service php-fpm restart
After restarting, you can view the PHP slow log with:
cd /var/log/php/ tail -f php-slow.log
Enabling slow logs for MySQL and PHP helps quickly identify performance bottlenecks in queries and scripts, allowing focused optimizations to improve overall system responsiveness and stability.