How to enable the MySQL slow query log?

To enable the slow query log in MySQL, you need to configure it in the MySQL configuration file. The steps are as follows:

  1. Locate the MySQL configuration file my.cnf, typically found in /etc/mysql/my.cnf or /etc/my.cnf.
  2. Open the configuration file and add the following settings under the [mysqld] section.
slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 1

The configuration here is to enable the slow query log, specify the slow query log file path as /var/log/mysql/mysql-slow.log, and set the time threshold for slow queries to 1 second.

  1. Save the configuration file and restart the MySQL service:
sudo systemctl restart mysql
  1. To ensure that MySQL has permission to write to log files, you can use the following command to grant permissions to the log files:
sudo chown mysql:mysql /var/log/mysql/mysql-slow.log
  1. View the slow query log. The slow query log in MySQL records SQL queries that exceed the long_query_time value in execution time, and you can optimize the database performance by viewing the slow query log.
bannerAds