您的位置:首页 > 数据库 > MySQL

mysql slow log 简单统计

2017-08-12 15:18 246 查看
众所周知,mysql slow log中很多sql 语句结构和对象是相同,只是其中变量不一样,对于这样的sql,我们完全可以将其归为一类,统计其执行次数、执行时间平均值等参数,而pt-query-digest恰好就是这样一款工具,能够对slow sql 进行归类、分组和分析,统计同一类sql多次运行后的参数:max、min、avg、count等:

# Query 6: 0.23QPS, 1.07x concurrency, ID 0x7F4D624CEA244E17 at byte 17591954
# This item isincluded in the report because it matches --limit.
# Scores: V/M =3.20
# Time range: 2016-08-0814:41:43 to 14:48:23
# Attribute    pct  total   min   max  avg  95%  stddev median
# ============ ========== ======= ======= ======= ======= ======= ===     ====
# Count       0     94
# Exec time     0   426s   2s   29s   5s  9s   4s   3s
# Lock time     0   23ms   75us   4ms  239us 384us  506us  138us
# Rows sent     0   94      1  1      1       1       0      1
# Rows examine   0    94       1       1      1       1       0      1
# Query size     0  6.28k      68     70   68.43   69.19      1   65.89
# String:
# Databases   test
# Hosts     192.168.1.19(35/37%),  192.168.1.20(33/35%)... 1 more
# Users     test
# Query_timedistribution
#  1us
#  10us
# 100us
#  1ms
#  10ms
# 100ms
#  1s ################################################################
#  10s+ ###
# Tables
#    SHOW TABLE STATUS FROM `test` LIKE 'user \G
#    SHOW CREATE TABLE `test`.`user`\G
# EXPLAIN /*!50100PARTITIONS*/
select * from userwhere periods = 'before' limit 1\G


最后,pt-query-digest还能对归类结果进行基于sql执行时间的max、min或者sum的排序统计
但是,如果我要截取query time top 10的 sql,根据max进行排序,并不科学,对于执行多次的sql,更
合理的应该是使用query time的中位值median进行排序,而前文显示的统计结果中,在Exec time一行中也恰好给出了每一类sql的执行时间的median值。
因此,为得到的更合理的结果,应根据median过滤获取最终结果

#首先使用pt-query-digest生成统计文件
/usr/local/bin/pt-query-digest slow.log >slow_log_report.log

#上述的统计包括了所有的sql,在这里只截取Query time:median >6s的sql

#!/bin/bash

file='slow_log_report.log'
median_linenum_array=(`cat $file |grep -n "^# Exec time" |awk '{if($11>6) print $1}'|cut -d: -f1`)

for((i=0;i<${#median_linenum_array[@]};i++));
do
start_linenum_array[$i]=$(( ${median_linenum_array[$i]} - 7 ))
end_linenum_array[$i]=`awk 'NR>='''$(( ${start_linenum_array[$i]} + 1 ))'''&&/^# Query [1-9]+/{print NR-1;exit}' $file`
sed -n ''''${start_linenum_array[$i]}''','''${end_linenum_array[$i]}'''p' $file>>slowlog_report_top.log
done


需要注意的是,media只有sql 语句执行次数多的时候才有统计意义,如果执行的很少,只有一两次,那media就没有意义了,所以,最终还是要结合count和median进行筛选
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  slow log mysql