首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

MySQL 5.5 開啟慢查詢日志完整指南:log_slow_queries 配置與分析

     編輯:MySQL 資料庫相關知識

動態開啟(無需重啟)

SET GLOBAL log_slow_queries = ON;
SET GLOBAL long_query_time = 0.2;              -- 閾值 0.2 秒(支援毫秒)
SET GLOBAL log_queries_not_using_indexes = ON; -- 記錄無索引查詢

查看日志輸出目標

SHOW VARIABLES LIKE 'log_output';
-- FILE:寫文件(默認)
-- TABLE:寫 mysql.slow_log 表

log_output 變量

切換輸出目標

SET GLOBAL log_output = 'TABLE';  -- 或 'FILE,TABLE' 並行

slow_log 表結構

查看慢查詢文件路徑

SHOW VARIABLES LIKE 'slow_query_log_file';

慢查詢文件路徑

永久配置(my.cnf)

[mysqld]
log_slow_queries = /var/log/mysql/slow.log
long_query_time = 2
log_queries_not_using_indexes = ON
log_output = FILE

mysqldumpslow 分析工具

# 按查詢次數排序,顯示前 10
mysqldumpslow -s c -t 10 /var/log/mysql/slow.log

# 按返回行數排序
mysqldumpslow -s r -t 10 /var/log/mysql/slow.log

# 按耗時排序,過濾 LEFT JOIN
mysqldumpslow -s t -t 10 -g "left join" /var/log/mysql/slow.log

參數說明

參數含義
-s c/t/l/r按次數/時間/查詢時間/返回行數排序
-t NTop N
-g "pattern"正則過濾(不區分大小寫)

日志字段解讀

Time: 120815 23:22:11
User@Host: root[root] @ localhost []
Query_time: 9.869362  Lock_time: 0.000035  Rows_sent: 1  Rows_examined: 6261774
SET timestamp=1294388531;
select count(*) from blog;
  • Query_time:SQL 執行耗時(核心指標)
  • Lock_time:Server 層鎖等待時間
  • Rows_examined:掃描行數(大於 Rows_sent 說明未命中索引)

最佳實踐

  • 生產環境 long_query_time = 1-2 秒
  • 不建議開啟 log_queries_not_using_indexes(產生大量垃圾日志)
  • 定期 mysqldumpslow 分析 + EXPLAIN 優化
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved