慢查詢日誌分析(mysql)

開啓慢查詢日誌以後,慢查詢sql會被存到數據庫系統表mysql.slow_log或是文件中,可參考。有兩個工具能夠幫助咱們分析輸出報告,分別是mysqldumpslow和pt-query-digest.html

mysqldumpslowmysql

mysqldumpslow是mysql自身提供的日誌分析工具,通常在mysql的bin目錄下git

幫助信息sql

 1 $ mysqldumpslow.pl --help
 2 Usage: mysqldumpslow [ OPTS... ] [ LOGS... ]
 3 
 4 Parse and summarize the MySQL slow query log. Options are
 5 
 6   --verbose    verbose
 7   --debug      debug
 8   --help       write this text to standard output
 9 
10   -v           verbose
11   -d           debug
12   -s ORDER     what to sort by (al, at, ar, c, l, r, t), 'at' is default
13                 al: average lock time
14                 ar: average rows sent
15                 at: average query time
16                  c: count
17                  l: lock time
18                  r: rows sent
19                  t: query time
20   -r           reverse the sort order (largest last instead of first)
21   -t NUM       just show the top n queries
22   -a           don't abstract all numbers to N and strings to 'S'
23   -n NUM       abstract numbers with at least n digits within names
24   -g PATTERN   grep: only consider stmts that include this string
25   -h HOSTNAME  hostname of db server for *-slow.log filename (can be wildcard),
26                default is '*', i.e. match all
27   -i NAME      name of server instance (if using mysql.server startup script)
28   -l           don't subtract lock time from total time
 1 -s, 是表示按照何種方式排序
 2     c: 訪問計數
 3  
 4     l: 鎖定時間
 5  
 6     r: 返回記錄
 7  
 8     t: 查詢時間
 9  
10     al:平均鎖定時間
11  
12     ar:平均返回記錄數
13  
14     at:平均查詢時間
15  
16 -t, 是top n的意思,即爲返回前面多少條的數據;
17 -g, 後邊能夠寫一個正則匹配模式,大小寫不敏感的;
18  
19 好比:
20 獲得返回記錄集最多的10個SQL。
21 mysqldumpslow -s r -t 10 /database/mysql/mysql06_slow.log
22  
23 獲得訪問次數最多的10個SQL
24 mysqldumpslow -s c -t 10 /database/mysql/mysql06_slow.log
25  
26 獲得按照時間排序的前10條裏面含有左鏈接的查詢語句。
27 mysqldumpslow -s t -t 10 -g 「left join」 /database/mysql/mysql06_slow.log
28  
29 另外建議在使用這些命令時結合 | 和more 使用 ,不然有可能出現刷屏的狀況。
30 mysqldumpslow -s r -t 20 /mysqldata/mysql/mysql06-slow.log | more

若是不能執行,能夠先安裝perl,而後經過perl mysqldumpslow xxx.logshell

 

pt-query-digest 參考數據庫

我的覺的pt-query-digest分析報告比mysqldumpslow好用。pt-query-digest能夠不只能夠分析slowlog,還能夠分析binlog,generallog等。json

下載安裝 https://www.percona.com/downloads/percona-toolkit/LATEST/windows

在windows下,下載tar.gz包,解壓以後,使用perl命令運行服務器

 

幫助信息併發

$ perl pt-query-digest --help
pt-query-digest analyzes MySQL queries from slow, general, and binary log files.
It can also analyze queries from C<SHOW PROCESSLIST> and MySQL protocol data
from tcpdump.  By default, queries are grouped by fingerprint and reported in
descending order of query time (i.e. the slowest queries first).  If no C<FILES>
are given, the tool reads C<STDIN>.  The optional C<DSN> is used for certain
options like L<"--since"> and L<"--until">.  For more details, please use the
--help option, or try 'perldoc pt-query-digest' for complete documentation.

Usage: pt-query-digest [OPTIONS] [FILES] [DSN]

Options:

  --ask-pass                   Prompt for a password when connecting to MySQL
  --attribute-aliases=a        List of attribute|alias,etc (default db|Schema)
  --attribute-value-limit=i    A sanity limit for attribute values (default 0)
  --charset=s              -A  Default character set
  --config=A                   Read this comma-separated list of config files;
                               if specified, this must be the first option on
                               the command line
  --[no]continue-on-error      Continue parsing even if there is an error (
                               default yes)
  --[no]create-history-table   Create the --history table if it does not exist (
                               default yes)
  --[no]create-review-table    Create the --review table if it does not exist (
                               default yes)
  --daemonize                  Fork to the background and detach from the shell
  --database=s             -D  Connect to this database
  --defaults-file=s        -F  Only read mysql options from the given file
  --embedded-attributes=a      Two Perl regex patterns to capture pseudo-
                               attributes embedded in queries
  --expected-range=a           Explain items when there are more or fewer than
                               expected (default 5,10)
  --explain=d                  Run EXPLAIN for the sample query with this DSN
                               and print results
  --filter=s                   Discard events for which this Perl code doesn't
                               return true
  --group-by=A                 Which attribute of the events to group by (
                               default fingerprint)
  --help                       Show help and exit
  --history=d                  Save metrics for each query class in the given
                               table. pt-query-digest saves query metrics (
                               query time, lock time, etc.) to this table so
                               you can see how query classes change over time
  --host=s                 -h  Connect to host
  --ignore-attributes=a        Do not aggregate these attributes (default arg,
                               cmd, insert_id, ip, port, Thread_id, timestamp,
                               exptime, flags, key, res, val, server_id,
                               offset, end_log_pos, Xid)
  --inherit-attributes=a       If missing, inherit these attributes from the
                               last event that had them (default db,ts)
  --interval=f                 How frequently to poll the processlist, in
                               seconds (default .1)
  --iterations=i               How many times to iterate through the collect-
                               and-report cycle (default 1)
  --limit=A                    Limit output to the given percentage or count (
                               default 95%:20)
  --log=s                      Print all output to this file when daemonized
  --order-by=A                 Sort events by this attribute and aggregate
                               function (default Query_time:sum)
  --outliers=a                 Report outliers by attribute:percentile:count (
                               default Query_time:1:10)
  --output=s                   How to format and print the query analysis
                               results (default report)
  --password=s             -p  Password to use when connecting
  --pid=s                      Create the given PID file
  --port=i                 -P  Port number to use for connection
  --preserve-embedded-numbers  Preserve numbers in database/table names when
                               fingerprinting queries
  --processlist=d              Poll this DSN's processlist for queries, with --
                               interval sleep between
  --progress=a                 Print progress reports to STDERR (default time,
                               30)
  --read-timeout=m             Wait this long for an event from the input; 0 to
                               wait forever (default 0).  Optional suffix s=
                               seconds, m=minutes, h=hours, d=days; if no
                               suffix, s is used.
  --[no]report                 Print query analysis reports for each --group-by
                               attribute (default yes)
  --report-all                 Report all queries, even ones that have been
                               reviewed
  --report-format=A            Print these sections of the query analysis
                               report (default rusage,date,hostname,files,
                               header,profile,query_report,prepared)
  --report-histogram=s         Chart the distribution of this attribute's
                               values (default Query_time)
  --resume=s                   If specified, the tool writes the last file
                               offset, if there is one, to the given filename
  --review=d                   Save query classes for later review, and don't
                               report already reviewed classes
  --run-time=m                 How long to run for each --iterations.  Optional
                               suffix s=seconds, m=minutes, h=hours, d=days; if
                               no suffix, s is used.
  --run-time-mode=s            Set what the value of --run-time operates on (
                               default clock)
  --sample=i                   Filter out all but the first N occurrences of
                               each query
  --set-vars=A                 Set the MySQL variables in this comma-separated
                               list of variable=value pairs
  --show-all=H                 Show all values for these attributes
  --since=s                    Parse only queries newer than this value (parse
                               queries since this date)
  --slave-password=s           Sets the password to be used to connect to the
                               slaves
  --slave-user=s               Sets the user to be used to connect to the slaves
  --socket=s               -S  Socket file to use for connection
  --timeline                   Show a timeline of events
  --type=A                     The type of input to parse (default slowlog)
  --until=s                    Parse only queries older than this value (parse
                               queries until this date)
  --user=s                 -u  User for login if not current user
  --variations=A               Report the number of variations in these
                               attributes' values
  --version                    Show version and exit
  --[no]version-check          Check for the latest version of Percona Toolkit,
                               MySQL, and other programs (default yes)
  --[no]vertical-format        Output a trailing "\G" in the reported SQL
                               queries (default yes)
  --watch-server=s             This option tells pt-query-digest which server
                               IP address and port (like "10.0.0.1:3306") to
                               watch when parsing tcpdump (for --type tcpdump);
                               all other servers are ignored

Option types: s=string, i=integer, f=float, h/H/a/A=comma-separated list, d=DSN, z=size, m=time

Rules:

  This tool accepts additional command-line arguments. Refer to the SYNOPSIS and usage information for details.

DSN syntax is key=value[,key=value...]  Allowable DSN keys:

  KEY  COPY  MEANING
  ===  ====  =============================================
  A    yes   Default character set
  D    yes   Default database to use when connecting to MySQL
  F    yes   Only read default options from the given file
  P    yes   Port number to use for connection
  S    yes   Socket file to use for connection
  h    yes   Connect to host
  p    yes   Password to use when connecting
  t    no    The --review or --history table
  u    yes   User for login if not current user

  If the DSN is a bareword, the word is treated as the 'h' key.

Options and values after processing arguments:

  --ask-pass                   FALSE
  --attribute-aliases          db|Schema
  --attribute-value-limit      0
  --charset                    (No value)
  --config                     /etc/percona-toolkit/percona-toolkit.conf,/etc/percona-toolkit/pt-query-digest.conf,/c/Users/Admin/.percona-toolkit.conf,/c/Users/Admin/.pt-query-digest.conf
  --continue-on-error          TRUE
  --create-history-table       TRUE
  --create-review-table        TRUE
  --daemonize                  FALSE
  --database                   (No value)
  --defaults-file              (No value)
  --embedded-attributes        (No value)
  --expected-range             5,10
  --explain                    (No value)
  --filter                     (No value)
  --group-by                   fingerprint
  --help                       TRUE
  --history                    (No value)
  --host                       (No value)
  --ignore-attributes          arg,cmd,insert_id,ip,port,Thread_id,timestamp,exptime,flags,key,res,val,server_id,offset,end_log_pos,Xid
  --inherit-attributes         db,ts
  --interval                   .1
  --iterations                 1
  --limit                      95%:20
  --log                        (No value)
  --order-by                   Query_time:sum
  --outliers                   Query_time:1:10
  --output                     report
  --password                   (No value)
  --pid                        (No value)
  --port                       (No value)
  --preserve-embedded-numbers  FALSE
  --processlist                (No value)
  --progress                   time,30
  --read-timeout               0
  --report                     TRUE
  --report-all                 FALSE
  --report-format              rusage,date,hostname,files,header,profile,query_report,prepared
  --report-histogram           Query_time
  --resume                     (No value)
  --review                     (No value)
  --run-time                   (No value)
  --run-time-mode              clock
  --sample                     (No value)
  --set-vars
  --show-all
  --since                      (No value)
  --slave-password             (No value)
  --slave-user                 (No value)
  --socket                     (No value)
  --timeline                   FALSE
  --type                       slowlog
  --until                      (No value)
  --user                       (No value)
  --variations
  --version                    FALSE
  --version-check              TRUE
  --vertical-format            TRUE
  --watch-server               (No value)
View Code
pt-query-digest [OPTIONS] [FILES] [DSN]
--create-review-table  當使用--review參數把分析結果輸出到表中時,若是沒有表就自動建立。
--create-history-table  當使用--history參數把分析結果輸出到表中時,若是沒有表就自動建立。
--filter  對輸入的慢查詢按指定的字符串進行匹配過濾後再進行分析
--limit    限制輸出結果百分比或數量,默認值是20,即將最慢的20條語句輸出,若是是50%則按總響應時間佔比從大到小排序,輸出到總和達到50%位置截止。
--host  mysql服務器地址
--user  mysql用戶名
--password  mysql用戶密碼
--history 將分析結果保存到表中,分析結果比較詳細,下次再使用--history時,若是存在相同的語句,且查詢所在的時間區間和歷史表中的不一樣,則會記錄到數據表中,能夠經過查詢同一CHECKSUM來比較某類型查詢的歷史變化。
--review 將分析結果保存到表中,這個分析只是對查詢條件進行參數化,一個類型的查詢一條記錄,比較簡單。當下次使用--review時,若是存在相同的語句分析,就不會記錄到數據表中。
--output 分析結果輸出類型,值能夠是report(標準分析報告)、slowlog(Mysql slow log)、json、json-anon,通常使用report,以便於閱讀。
--since 從什麼時間開始分析,值爲字符串,能夠是指定的某個」yyyy-mm-dd [hh:mm:ss]」格式的時間點,也能夠是簡單的一個時間值:s(秒)、h(小時)、m(分鐘)、d(天),如12h就表示從12小時前開始統計。
--until 截止時間,配合—since能夠分析一段時間內的慢查詢。

輸出結果分析

分爲三部分

第一部分 整體統計結果

overall:總共統計結果

time range:查詢執行的時間範圍

unique:惟一查詢數量,即對查詢條件進行參數化之後,總共有多少個不一樣的查詢

total:總計

min:最小

max:最大

avg:平均

95%:把全部值從小到大排列,位置位於95%的那個數,這個數通常最具參考價值

median:中位數,把全部值從小到大排列,位置位於中間那個數

# 該工具執行日誌分析的用戶時間,系統時間,物理內存佔用大小,虛擬內存佔用大小
# 343ms user time, 78ms system time, 0 rss, 0 vsz
# 工具執行時間
# Current date: Thu Mar 29 15:51:38 2018
# 運行分析工具的主機名
# Hostname: NB2015041602
# 被分析的文件名
# Files: /d/xampp/mysql/data/NB2015041602-slow.log
# 語句總數量,惟一的語句數量,QPS,併發數
# Overall: 5 total, 3 unique, 0.00 QPS, 0.05x concurrency ________________
# 日誌記錄的時間範圍
# Time range: 2018-03-28 14:02:06 to 14:22:10
# 屬性               總計      最小    最大    平均    95%  標準    中等
# Attribute          total     min     max     avg     95%  stddev  median
# ============     ======= ======= ======= ======= ======= ======= =======
# 語句執行時間
# Exec time            60s     10s     17s     12s     17s      3s     11s
# 鎖佔用時間
# Lock time            1ms       0   500us   200us   490us   240us       0
# 發送到客戶端的行數
# Rows sent             50      10      10      10      10       0      10
# select語句掃描行數
# Rows examine     629.99k  45.43k 146.14k 126.00k 143.37k  39.57k 143.37k
# 查詢的字符數
# Query size         2.81k     235   1.36k  575.40   1.33k  445.36  234.30

第二部分 查詢分組統計結果

rank:全部語句的排序,默認按照查詢時間降序排序,經過--order-by指定

query id:語句的id,(去掉多餘空格和文本字符,計算hash值)

response:總的響應時間

time:該查詢在本次分析中總的時間佔比

calls:執行次數,即本次分析總共有多少條這種類型的查詢語句

r/call:平均每次執行的響應時間

v/m:響應時間variance-to-mean的比率

item:查詢對象

# Profile
# Rank Query ID           Response time Calls R/Call  V/M   Item
# ==== ================== ============= ===== ======= ===== ==============
#    1 0x96112A601F7BCCC0 32.9042 55.0%     3 10.9681  0.01 SELECT affiliatemerchant_list user_list
#    2 0x70885F9703A0E38D 17.2162 28.8%     1 17.2162  0.00 SELECT normalmerchant merchant_mapping normalmerchant_addinfo merchant_search_filter affiliatemerchant_list user_list
#    3 0x43D8527285567FC4  9.7367 16.3%     1  9.7367  0.00 SELECT affiliatemerchant_list user_list affiliatemerchant_list user_list

 

第三部分 每一種查詢的詳細統計結果

id:查詢的id號,和上面的query id對應

databases:數據庫名

users:各個用戶執行的次數(佔比)

query_time_distribution:查詢時間分佈,長短體現區間佔比

tables:查詢中設計到的表

explain:sql語句

# Query 1: 0.00 QPS, 0.03x concurrency, ID 0x96112A601F7BCCC0 at byte 2647
# This item is included in the report because it matches --limit.
# Scores: V/M = 0.01
# Time range: 2018-03-28 14:03:31 to 14:19:54
# Attribute    pct   total     min     max     avg     95%  stddev  median
# ============ === ======= ======= ======= ======= ======= ======= =======
# Count         60       3
# Exec time     54     33s     11s     11s     11s     11s   243ms     11s
# Lock time     50   500us       0   500us   166us   490us   231us       0
# Rows sent     60      30      10      10      10      10       0      10
# Rows examine  69 438.42k 146.14k 146.14k 146.14k 146.14k       0 146.14k
# Query size    24     707     235     236  235.67  234.30       0  234.30
# String:
# Databases    database_base
# Hosts        localhost
# Users        root
# Query_time distribution
#   1us
#  10us
# 100us
#   1ms
#  10ms
# 100ms
#    1s
#  10s+  ################################################################
# Tables
#    SHOW TABLE STATUS FROM `database_base` LIKE 'table_list1'\G
#    SHOW CREATE TABLE `database_base`.`table_list1`\G
#    SHOW TABLE STATUS FROM `database_base` LIKE 'user_list'\G
#    SHOW CREATE TABLE `database_base`.`user_list`\G
# EXPLAIN /*!50100 PARTITIONS*/
select SQL_CALC_FOUND_ROWS al.*, ul.Alias as userName
        FROM table_list1 al
        LEFT JOIN user_list ul ON ul.ID = al.UserId
         WHERE TRUE  AND (al.SupportCountrys LIKE '%%')
        
         limit 80, 10\G

 

pt-query-digest用法示例(未測試)

直接分析慢查詢文件
pt-query-digest  slow.log > slow_report.log

分析最近12小時內的查詢
pt-query-digest  --since=12h  slow.log > slow_report2.log

分析指定時間範圍內的查詢
pt-query-digest slow.log --since '2017-01-07 09:30:00' --until '2017-01-07 10:00:00'> > slow_report3.log

分析含有select語句的慢查詢
pt-query-digest --filter '$event->{fingerprint} =~ m/^select/i' slow.log> slow_report4.log

針對某個用戶的慢查詢
pt-query-digest --filter '($event->{user} || "") =~ m/^root/i' slow.log> slow_report5.log

查詢全部全表掃描或full join的慢查詢
pt-query-digest --filter '(($event->{Full_scan} || "") eq "yes") ||(($event->{Full_join} || "") eq "yes")' slow.log> slow_report6.log

把查詢保存到query_review表
pt-query-digest --user=root –password=abc123 --review  h=localhost,D=test,t=query_review--create-review-table  slow.log

把查詢保存到query_history表
pt-query-digest  --user=root –password=abc123 --review  h=localhost,D=test,t=query_history--create-review-table  slow.log_0001
pt-query-digest  --user=root –password=abc123 --review  h=localhost,D=test,t=query_history--create-review-table  slow.log_0002

經過tcpdump抓取的tcp協議數據,而後分析
tcpdump -s 65535 -x -nn -q -tttt -i any -c 1000 port 3306 > mysql.tcp.txt
pt-query-digest --type tcpdump mysql.tcp.txt> slow_report9.log

分析biglog
mysqlbinlog mysql-bin.000093 > mysql-bin000093.sql
pt-query-digest  --type=binlog  mysql-bin000093.sql > slow_report10.log

分析general log
pt-query-digest  --type=genlog  localhost.log > slow_report11.log
相關文章
相關標籤/搜索