16 December 2013

Finding Slow Queries in MySQL

I have this web application I built. It's a test tool that performs a variety of checks of phone numbers and phone carriers. I noticed after a recent update that it began to load really slow (the web interface.) Instead of the usual 4 second load time, it was taking 30 seconds. I had indexed a variety of tables in the past, so I wasn't sure which query was causing the problem. What helped me find out the source of the problem was MySQL's slow log. In my default installation of MySQL, the slow logging is not on. To turn it on, I had to first edit the mysql config (which on Centos is somewhere like /etc/my.cnf) In the config file I added these lines under [mysqld]: log-slow-queries = /var/log/mysql/slow_query.log long_query_time = 10 log-queries-not-using-indexes Next, I created the folder /var/log/mysql and set the ownership to mysql: sudo chown mysql.mysql /var/log/mysql Inside the folder, I added a empty file: touch slow_query.log After doing all that, I restarted MySQL with /etc/init.d/mysql restart (which is the default CentOS way to restart mysql.) In the general mysql log (/var/log/mysqld.log) there should be no errors referencing the new slow log. The lines added to the my.cnf file basically say: when a query is slow, please log it in /var/log/mysql/slow_query.log by slow, I mean anything taking longer then 10 seconds also, log any queries not using an index. After restarting mysql and hitting the webpage, I saw the new slow log updated and found the culprit query causing my problems.

No comments:

Post a Comment