前言:以前介绍了通过工具MySQLdumpslow分析慢查询日志的方法,随着工作的进展又发现了另外一个更加好用的方法:把慢日志记录到mysql数据库中。
方法介绍:通过设置参数log_output可以定义mysql的慢查询日志是存放在文件还是数据表中;
mysql> show variables like 'log_output';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_output | FILE |
+---------------+-------+
1 row in set (0.00 sec)
注:Value值是输出的格式,当前的Value值为FILE说明把慢查询日志存放在OS的文件中;
mysql> set global log_output='TABLE';
Query OK, 0 rows affected (0.00 sec)
注:设置当前的输出为mysql中的表;
mysql> show variables like 'log_output';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_output | TABLE |
+---------------+-------+
1 row in set (0.00 sec)
注:现在输出为mysql中的表了;
测试:
建议:slow_log创建时候默认的数据库引擎是CSV,该引擎的查询效率比较低,可以修改成MyISAM;
mysql> select * from mysql.slow_log;
CREATE TABLE `slow_log` (
`start_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`user_host` mediumtext NOT NULL,
`query_time` time NOT NULL,
`lock_time` time NOT NULL,
`rows_sent` int(11) NOT NULL,
`rows_examined` int(11) NOT NULL,
`db` varchar(512) NOT NULL,
`last_insert_id` int(11) NOT NULL,
`insert_id` int(11) NOT NULL,
`server_id` int(10) unsigned NOT NULL,
`sql_text` mediumtext NOT NULL
) ENGINE=CSV DEFAULT CHARSET=utf8 COMMENT='Slow log';
整理了一个常用的语句:使用次数进行排序慢查询的sql语句
mysql> select sql_text, count(1),avg(query_time),avg(rows_sent),avg(rows_examined)
from slow_log
group by (sql_text)
order by avg(query_time) desc