#!/usr/bin/env bash # slow_log_digest.sh: run pt-query-digest on the last N minutes of mysql.slow_log (log_output=TABLE) # Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/) # https://hashjoin.com/kb/mysql/pt-query-digest-rds-slow-log-table/ # # Usage: slow_log_digest.sh MINUTES [--extract-only] [-- MYSQL_CLIENT_OPTIONS...] # # MINUTES how far back to read mysql.slow_log # --extract-only write the slow-log file and stop (run pt-query-digest elsewhere) # -- ... passed to the mysql client: --defaults-file=..., --host=..., etc. # # Writes slow_-min.log (the rows rebuilt in slow-log file format) and # digest_-min.txt (the pt-query-digest report) to $OUT_DIR (default: .). # PT_QUERY_DIGEST names the pt-query-digest command (default: pt-query-digest). # # Every 5 minutes, overlapping a little so nothing falls between runs: # */5 * * * * cd /opt/slowlog && ./slow_log_digest.sh 7 -- --defaults-file=.my.cnf --host=mydb.xxxx.rds.amazonaws.com set -euo pipefail MIN="${1:?usage: $0 MINUTES [--extract-only] [-- mysql options]}"; shift case "$MIN" in ''|*[!0-9]*) echo "MINUTES must be a whole number" >&2; exit 2 ;; esac EXTRACT_ONLY=no while [ $# -gt 0 ]; do case "$1" in --extract-only) EXTRACT_ONLY=yes; shift ;; --) shift; break ;; *) echo "usage: $0 MINUTES [--extract-only] [-- mysql options]" >&2; exit 2 ;; esac done OUT_DIR="${OUT_DIR:-.}" STAMP=$(date +%Y%m%d_%H%M%S) LOG="$OUT_DIR/slow_${STAMP}-${MIN}min.log" REP="$OUT_DIR/digest_${STAMP}-${MIN}min.txt" # One slow-log entry per row, in the format pt-query-digest parses. query_time and lock_time # are TIME(6). The seconds are built from their parts with all six decimals: TIME_TO_SEC() # drops the fraction, and dividing MICROSECOND() by 1000000 rounds to four places, so a # 0.07 ms query would read 0.0001 or 0. The session runs in UTC so the "# Time:" lines can # say so. mysql "$@" --batch --raw --skip-column-names -e " SET time_zone = '+00:00'; SELECT CONCAT( '# Time: ', DATE_FORMAT(start_time, '%Y-%m-%dT%H:%i:%s.%fZ'), '\n', '# User@Host: ', user_host, ' Id: ', thread_id, '\n', '# Query_time: ', HOUR(query_time) * 3600 + MINUTE(query_time) * 60 + SECOND(query_time), '.', LPAD(MICROSECOND(query_time), 6, '0'), ' Lock_time: ', HOUR(lock_time) * 3600 + MINUTE(lock_time) * 60 + SECOND(lock_time), '.', LPAD(MICROSECOND(lock_time), 6, '0'), ' Rows_sent: ', rows_sent, ' Rows_examined: ', rows_examined, '\n', IF(db IS NULL OR db = '', '', CONCAT('use ', db, ';\n')), 'SET timestamp=', FLOOR(UNIX_TIMESTAMP(start_time)), ';\n', TRIM(TRAILING ';' FROM CONVERT(sql_text USING utf8mb4)), ';') FROM mysql.slow_log WHERE start_time >= NOW() - INTERVAL ${MIN} MINUTE ORDER BY start_time" > "$LOG" echo "$(date): $(grep -c '^# Time: ' "$LOG" || true) slow-log entries in the last ${MIN} minutes -> $LOG" [ "$EXTRACT_ONLY" = yes ] && exit 0 ${PT_QUERY_DIGEST:-pt-query-digest} --limit 100% "$LOG" > "$REP" echo "$(date): report -> $REP"