首先介绍下什么是慢日志:
慢查询日志是mysql提供的将执行时间超过long_query_time的值的sql记录到慢查询日志中,long_query_time的最小值为0,默认值是10S;默认情况下慢日志不开启,倘若我们调优需要,可以手动设置这个参数,开启慢日志。一般情况不建议开启,毕竟开启慢日志多少都会对mysql性能造成一定影响。
官网介绍:https://dev.mysql.com/doc/refman/5.7/en/slow-query-log.html
官网主要描述:
The slow query log consists of SQL statements that took more than long_query_time seconds to execute and required at least min_examined_row_limit rows to be examined. The minimum and default values of long_query_time are 0 and 10, respectively. The value can be specified to a resolution of microseconds. For logging to a file, times are written including the microseconds part. For logging to tables, only integer times are written; the microseconds part is ignored.
配置文件(my.ini、my.cnf)中相关配置
slow_query_log : 否开启慢查询日志 1开启 0关闭
long_query_time : 设定慢查询的阀值,超出设定值的SQL即被记录到慢查询日志,默认值为10s
log_slow_queries : 指定慢日志文件存放位置(5.6以下使用,5.6以上该参数被slow_query_log_file取代,做兼容性保留)
slow_query_log_file : 指定慢日志文件存放位置 默认存储在:host_name-slow.log
log_queries_not_using_indexes: 不使用索引的慢查询日志是否记录到索引 可不设置
查看当前慢日志是否开启
mysql> show variables like '%slow_query_log%';
+---------------------+-----------------------------------------------------+
| Variable_name | Value |
+---------------------+-----------------------------------------------------+
| slow_query_log | OFF |
| slow_query_log_file | /usr/local/var/mysql/jixinxindeMacBook-Pro-slow.log |
+---------------------+-----------------------------------------------------+
2 rows in set (0.01 sec)
主要看 low_query_log 值 值为OFF表示关闭。
慢查询日志开启方式有两种:
1、mysql命令行:
set global slow_query_log=1;这种方式开启后只对当前数据库生效,重启后会失效。
mysql> set global slow_query_log=1;
Query OK, 0 rows affected (0.02 sec)
mysql> show variables like '%slow_query_log%';
+---------------------+-----------------------------------------------------+
| Variable_name | Value |
+---------------------+-----------------------------------------------------+
| slow_query_log | ON |
| slow_query_log_file | /usr/local/var/mysql/jixinxindeMacBook-Pro-slow.log |
+---------------------+-----------------------------------------------------+
2 rows in set (0.00 sec)
2、修改配置文件my.cnf
slow_query_log=1
其他参数根据实际情况进行具体设置。
倘若我们不做其他设置,这样我们就可以去host_name-slow.log中查看具体的慢查询sql了,然后针对具体sql进行调优。