vim /etc/my.cnf
[mysqld]
slow_query_log = 1
long_query_time = 1 #定义超过1秒的查询计数到slow_queries
log-queries-not-using-indexes #未使用索引的查询也记录到慢查询日志中(可选)
log-slow-queries = /var/log/mariadb/slow.log #定义慢查询日志位置
测试
mysql -u root -p
select sleep(2);
+----------+
| sleep(2) |
+----------+
| 0 |
+----------+
1 row in set (2.01 sec)
MariaDB [(none)]> quit
cat /var/log/mariadb/slow.log
/usr/libexec/mysqld, Version: 5.5.56-MariaDB (MariaDB Server). started with:
Tcp port: 3306 Unix socket: /var/lib/mysql/mysql.sock
Time Id Command Argument
# Time: 180223 10:46:32
# [email protected]: root[root] @ localhost []
# Thread_id: 2 Schema: QC_hit: No
# Query_time: 2.003322 Lock_time: 0.000000 Rows_sent: 1 Rows_examined: 0
SET timestamp=1519353992;
select sleep(2);
mariadb提供了慢查询分析工具mysqldumpslow,可以按时间或出现次数统计慢查询的情况
-s 排序参数 al平均锁定时间,ar平均返回记录数,at平均查询时间
-t 只显示指定行数
例:mysqldumpslow -s t /var/log/mariadb/slow.log
得到查询时间最长的查询
Reading mysql slow query log from /var/log/mariadb/slow.log
Count: 1 Time=2.00s (2s) Lock=0.00s (0s) Rows_sent=1.0 (1), Rows_examined=0.0 (0), root[root]@localhost
select sleep(N)