1、登录MySQL服务器,查看慢查询日志是否开启
命令:
mysql> show variables like ‘%slow_query_log%‘; +---------------------+------------------------------+ | Variable_name | Value | +---------------------+------------------------------+ | slow_query_log | OFF | | slow_query_log_file | /var/lib/mysql/peng-slow.log | +---------------------+------------------------------+ 2 rows in set (0.00 sec)
2、开启慢查询日志
命令:
mysql> set global slow_query_log = 1; Query OK, 0 rows affected (0.00 sec) mysql> show variables like ‘%slow_query_log%‘; +---------------------+------------------------------+ | Variable_name | Value | +---------------------+------------------------------+ | slow_query_log | ON | | slow_query_log_file | /var/lib/mysql/peng-slow.log | +---------------------+------------------------------+ 2 rows in set (0.00 sec)
3、查看慢查询日志中的最大忍耐时间(默认:10s)
命令:
mysql> show variables like ‘%long_query_time%‘; +-----------------+-----------+ | Variable_name | Value | +-----------------+-----------+ | long_query_time | 10.000000 | +-----------------+-----------+ 1 row in set (0.00 sec)
4、设置慢查询日志中的最大忍耐时间
命令:
mysql> set global long_query_time = 3; Query OK, 0 rows affected (0.00 sec) mysql> show variables like ‘%long_query_time%‘; +-----------------+-----------+ | Variable_name | Value | +-----------------+-----------+ | long_query_time | 10.000000 | +-----------------+-----------+ 1 row in set (0.00 sec)
mysql> show global variables like ‘%long_query_time%‘;
+-----------------+----------+
| Variable_name | Value |
+-----------------+----------+
| long_query_time | 3.000000 |
+-----------------+----------+
1 row in set (0.00 sec)
------------------------------------------------
新窗口,效果如下
mysql> show variables like ‘%long_query_time%‘;
+-----------------+----------+
| Variable_name | Value |
+-----------------+----------+
| long_query_time | 3.000000 |
+-----------------+----------+
1 row in set (0.00 sec)
如果设置完成之后,仍然在当前窗口查看的话,想要看到设置之后的效果
方式一:当前窗口下输入命令,在 show variables like ‘%long_query_time%’ 命令的show后面加上 global。
方式二:新起一个窗口(即会话),直接输入show variables like ‘%long_query_time%‘这个命令即可。
5、用下面一个睡眠命令来模拟实际应用场景中的慢SQL语句执行
命令:
mysql> select sleep(4); +----------+ | sleep(4) | +----------+ | 0 | +----------+ 1 row in set (4.00 sec)
6、查看慢查询日志文件
命令:
[root@peng mysql]# cat -n peng-slow.log 1 /usr/sbin/mysqld, Version: 5.5.48-log (MySQL Community Server (GPL)). started with: 2 Tcp port: 3306 Unix socket: /var/lib/mysql/mysql.sock 3 Time Id Command Argument 4 # Time: 210630 19:30:45 5 # User@Host: root[root] @ localhost [] 6 # Query_time: 4.000641 Lock_time: 0.000000 Rows_sent: 1 Rows_examined: 0 7 SET timestamp=1625052645; 8 select sleep(4); 9 /usr/sbin/mysqld, Version: 5.5.48-log (MySQL Community Server (GPL)). started with: 10 Tcp port: 3306 Unix socket: /var/lib/mysql/mysql.sock 11 Time Id Command Argument