这是一个纯脚本工具,用于从MySQL的information_schema.processlist
视图中定期收集数据并保存到本地日志文件。支持MYSQL5.7-9.4版本。
template copy from PostgreSQL version : https://github.com/yansheng836/pg_collect_pgsa .
相关背景:
- 某个慢SQL打满内存,导致系统kill掉mysql的进程,进而导致mysql进程重启,没有现场排查不了具体原因。(即使开启了慢SQL日志,没有执行完也不会记录到数据库日志中)
- 数据库连接数被打满,MYSQL相关监控数据丢失(因为也连不上数据库了),没有现场,不知道异常请求来源。
特性:
- 定期收集MySQL活动会话信息
- 支持通过定时任务配置收集频率
- 提供日志文件自动分割功能
- 包含丰富的日志分析示例
安装指南
拉取代码,修改参数,设置定时任务。
# 克隆代码
git clone git@github.com:yansheng836/mysql_collect_processlist.git
cd mysql_collect_processlist
# 修改必要参数(均以 MYSQL_ 开头,例如:MYSQL_PATH、MYSQL_HOST 等)
vi mysql_collect_processlist.sh
# 查路径
pwd
# crontab -e
# 每分钟执行
* * * * * sh pwd路径/mysql_collect_processlist.sh
# 如果需要更频繁,比如每5秒执行(可自行调整秒数)
* * * * * sh pwd路径/mysql_collect_processlist_gap_second.sh 5
日志文件内容
测试版本:mysql Ver 8.0.43 for Linux on x86_64 (MySQL Community Server - GPL)
CI版本:MYSQL5.7-9.4
输出字段为:now(),ID,USER,HOST,DB,COMMAND,TIME,STATE,INFO
2025-09-09 14:44:02|42|root|localhost|mysql|Query|0|executing|SELECT now(),ID,USER,HOST,DB,COMMAND,TIME,STATE,INFO from information_schema.processlist
2025-09-09 14:44:02|5|event_scheduler|localhost|NULL|Daemon|8000|Waiting on empty queue|NULL
日志分析参考
1.简单检索
# cat/more/less/grep
grep 'executing' processlist.log
# 查找具体时间的相关日志
grep '2025-09-04 12:59' processlist.log
# 在归档日志中,查找具体时间的相关日志
zless logs/processlist-20250904-12.log.gz | grep '2025-09-04 12:59'
2.统计不同状态的语句的数量
# 第8列是状态:state
awk -F '|' '{print $8}' processlist.log | sort | uniq -c
1 executing
1 Waiting on empty queue
3.按照时间统计
# 按天统计
awk -F '|' '{print $1}' processlist.log | cut -d ' ' -f1 | sort | uniq -c
2 2025-09-09
# 按小时统计
awk -F '[| ]' '{print $1 " " $2}' processlist.log | cut -d: -f1 | sort | uniq -c
2 2025-09-09 14
# 按分钟统计
awk -F '[| ]' '{print $1 " " $2}' processlist.log | cut -d: -f1-2 | sort | uniq -c
2 2025-09-09 14:44
注意事项
在业务繁忙的数据库上使用时,需要注意日志文件可能会快速增长,建议在特殊情况下短暂使用,并密切关注磁盘空间。
info
字段的长度受MySQL常量PROCESS_LIST_INFO_WIDTH
限制,默认为65535(写死在源码中),超出部分会被截断。(足以满足绝大多数场景。)账号权限问题,可不使用mysql。推荐最小权限:[创建空库,]创建普通用户,授予
PROCESS
权限即可。-- CREATE DATABASE processlist_db; GRANT PROCESS ON *.* TO 'processlist_user'@'hostname';
仓库
详见::
GitHub:https://github.com/yansheng836/mysql_collect_processlist/issues
Gitee:https://gitee.com/yansheng0083/mysql_collect_processlist/issues