慢查询日志拓展-如何开启MySQL慢查询日志?
1.查看MySQL慢查询日志是否开启?
show variables like '%query%';
查询出的结果中,主要观察如下三条:
-
long_query_time
通过long_query_time设置阈值,设置阈值后,MySQL数据库会记录运行时间超过该值的所有SQL语句,但是运行时间刚刚好等于
long_query_time
的情况并不会被记录。 -
slow_query_log
ON表示开启慢查询日志,OFF表示关闭慢查询日志
可以通过
set global slow_query_log=ON
开启,通过set global slow_query_log=OFF
关闭。 -
slow_query_log_file
记录慢查询日志文件的位置
mysql> show variables like '%query%';
+------------------------------+------------------------------------+
| Variable_name | Value |
+------------------------------+------------------------------------+
| long_query_time | 10.000000 |
| slow_query_log | OFF |
| slow_query_log_file | /var/lib/mysql/zxy_master-slow.log |
+------------------------------+------------------------------------+
13 rows in set (0.00 sec)
2.开启慢查询日志
set global slow_query_log=ON;
mysql> set global slow_query_log=ON;
Query OK, 0 rows affected (0.00 sec)
3.查看慢查询日志存储类型
show variables like '%log_output%';
-
set global log_output = ‘FILE’;
存储在磁盘目录中,可以通过参数
slow_query_log_file
查看。 -
set global log_output = ‘TABLE’;
存储在数据库中,可以通过查询
mysql.slow_log
查看;
mysql> show variables like '%log_output%';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_output | FILE |
+---------------+-------+
1 row in set (0.00 sec)
4.测试慢查询日志
4.1 log_output = ‘FILE’
# 1.设置慢查询格式为FILE
mysql> set global log_output = 'file';
Query OK, 0 rows affected (0.00 sec)
# 2.模拟慢查询11秒
mysql> select sleep(11);
+-----------+
| sleep(11) |
+-----------+
| 0 |
+-----------+
1 row in set (11.00 sec)
查询日志
[root@zxy_master mysql]# cat /var/lib/mysql/zxy_master-slow.log
# Time: 2023-01-09T01:48:59.330285Z
# User@Host: root[root] @ localhost [] Id: 1634
# Query_time: 11.000191 Lock_time: 0.000000 Rows_sent: 1 Rows_examined: 0
SET timestamp=1673228939;
select sleep(11);
4.2 log_output = ‘TABLE’
# 1.设置慢查询日志为TABLE
mysql> set global log_output = 'TABLE';
Query OK, 0 rows affected (0.00 sec)
# 2.模拟慢查询日志11秒
mysql> select sleep(11);
+-----------+
| sleep(11) |
+-----------+
| 0 |
+-----------+
1 row in set (11.00 sec)
查询日志
# 从mysql.slow_log表中查询日志
mysql> select * from mysql.slow_log\G;
*************************** 1. row ***************************
start_time: 2023-01-09 09:53:01.251772
user_host: root[root] @ localhost []
query_time: 00:00:11.000189
lock_time: 00:00:00.000000
rows_sent: 1
rows_examined: 0
db:
last_insert_id: 0
insert_id: 0
server_id: 1
sql_text: select sleep(11)
thread_id: 1634
1 row in set (0.00 sec)