如何使用正则匹配MySQL慢查询日志中root用户的查询记录
如何从MySQL慢查询日志中匹配并移除root用户的查询记录
问题场景
给定如下MySQL慢查询日志:
# Time: 230706 17:12:48 # User@Host: sample[sample] @ localhost [] # Thread_id: 626784 Schema: sample QC_hit: No # Query_time: 2.976557 Lock_time: 0.000178 Rows_sent: 0 Rows_examined: 3344231 # Rows_affected: 0 Bytes_sent: 195 SET timestamp=1688677968; SELECT * from a; # Time: 230706 17:15:51 # User@Host: root[root] @ localhost [] # Thread_id: 627770 Schema: sample QC_hit: No # Query_time: 2.581676 Lock_time: 0.000270 Rows_sent: 0 Rows_examined: 2432228 # Rows_affected: 0 Bytes_sent: 195 SET timestamp=1688678151; select * from cs; # Time: 230706 17:13:37 # User@Host: sample[sample] @ localhost [] # Thread_id: 627027 Schema: oiemorug_wp598 QC_hit: No # Query_time: 3.901325 Lock_time: 0.000145 Rows_sent: 0 Rows_examined: 3851050 # Rows_affected: 0 Bytes_sent: 195 SET timestamp=1688678017; SELECT * from b # Time: 230706 17:15:51 # User@Host: root[root] @ localhost [] # Thread_id: 627770 Schema: sample QC_hit: No # Query_time: 2.581676 Lock_time: 0.000270 Rows_sent: 0 Rows_examined: 2432228 # Rows_affected: 0 Bytes_sent: 195 SET timestamp=1688678151; select * from cs
需求是匹配所有由root用户发起的完整查询记录(即日志中包含User@Host: root[root]的条目),最终目的是从日志中移除这些记录。此前尝试的正则表达式效果不佳:
# Time.*?root.*?(?=# Time):会误匹配非root用户的记录# Time.*?root.*?(?!# Time):匹配结果不符合预期
解决方案
正确的正则表达式
使用以下正则可以精准匹配所有root用户的查询记录(需开启多行模式和单行模式,让.匹配换行符):
# Time:.*?User@Host: root\[root\].*?(?=# Time:|\Z)
正则解释
# Time::定位每个查询记录的起始标识.*?:非贪婪匹配到User@Host: root\[root\]的内容,避免跳过目标条目User@Host: root\[root\]:精准匹配root用户的特征行,\[和\]是转义后的方括号.*?(?=# Time:|\Z):非贪婪匹配到下一个查询记录的起始# Time:,或者日志结尾\Z,确保完整匹配整个root用户的查询条目
移除root记录的操作示例
如果使用sed命令处理日志文件(需支持扩展正则,加-E参数):
sed -E '/# Time:/{:a;N;/# Time:/!ba;/User@Host: root\[root\]/d}' slow_query.log > cleaned_slow_query.log
如果用文本编辑器(如VS Code):
- 打开慢查询日志,开启正则替换模式(勾选
.*匹配换行符) - 查找内容填入上述正则
- 替换内容留空,执行全部替换即可
内容的提问来源于stack exchange,提问作者Cesar
相关产品推荐
相关产品推荐

