mysql> show variables like '%slow_query_log%' +---------------------+-------------------------------+ | Variable_name | Value | +---------------------+-------------------------------+ | slow_query_log | OFF | | slow_query_log_file | /var/lib/mysql/mysql-slow.log | +---------------------+-------------------------------+ 2 rows in set (0.00 sec)
开启慢查询日志:
1 2
mysql> set global slow_query_log=1; Query OK, 0 rows affected (0.00 sec)
然后看状态:
1 2 3 4 5 6 7 8
mysql> show variables like '%slow_query_log%'; +---------------------+-------------------------------+ | Variable_name | Value | +---------------------+-------------------------------+ | slow_query_log | ON | | slow_query_log_file | /var/lib/mysql/mysql-slow.log | +---------------------+-------------------------------+ 2 rows in set (0.00 sec)
使用set global slow_query_log=1开启了慢查询日志只对当前数据库生效,如果MySQL重启后则会失效。如果要永久生效,就必须修改配置文件my.cnf(其它系统变量也是如此)。
例如如下所示:
1 2 3
[root@mysql ~]# vim /etc/my.cnf slow_query_log=1 slow_query_log_file=/var/lib/mysql/mysql-slow.log
参数说明:
slow_query_log 慢查询开启状态;
slow_query_log_file 慢查询日志存放的位置;
long_query_time查询超过多少秒才记录。
日志分析工具
MySQL 自带了一个查看慢日志的工具 mysqldumpslow,执行mysqldumpslow –help 可以查看其相关参数和说明:
Parse and summarize the MySQL slow query log. Options are
--verbose verbose --debug debug --help write this text to standard output
-v verbose -d debug -s ORDER what to sort by (al, at, ar, c, l, r, t), 'at' is default al: average lock time ar: average rows sent at: average query time c: count l: lock time r: rows sent t: query time -r reverse the sort order (largest last instead of first) -t NUM just show the top n queries -a don't abstract all numbers to N and strings to 'S' -n NUM abstract numbers with at least n digits within names -g PATTERN grep: only consider stmts that include this string -h HOSTNAME hostname of db server for *-slow.log filename (can be wildcard), default is '*', i.e. match all -i NAME name of server instance (if using mysql.server startup script) -l don't subtract lock time from total time