Mysql 设置 慢SQL时间并触发邮件

Mysql 设置 慢SQL时间,并触发邮件

1. 临时设置(会话级别)
sql 复制代码
SET SESSION long_query_time = 2; -- 设置慢查询时间为2秒
2. 全局设置
这样所有会话都会受到影响:
sql 复制代码
SET GLOBAL long_query_time = 2; -- 设置慢查询时间为2秒
3. 检查当前设置
sql 复制代码
SHOW VARIABLES LIKE 'long_query_time';
-- 或者
select @@long_query_time;

以上的问题,MySQL 服务重启后 失效。

4. 配置文件配置

为了确保设置在服务器重启后仍然有效,可以在 MySQL 配置文件(如 my.cnf 或 my.ini)中添加以下行:

ini 复制代码
[mysqld]
slow_query_log = 1
slow_query_log_file = /path/to/your/slow-query.log
long_query_time = 2  # 设置慢查询时间为2秒
log_queries_not_using_indexes = 1  # 可选:记录未使用索引的查询
5. 重启MySQL服务

保存配置文件并重启MySQL服务以使更改生效。

6. 编写Python 触发邮件代码
python 复制代码
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 配置邮件发送信息
SMTP_SERVER = 'smtp.example.com'
SMTP_PORT = 587
SMTP_USER = 'your-email@example.com'
SMTP_PASSWORD = 'your-email-password'
FROM_EMAIL = 'your-email@example.com'
TO_EMAIL = 'recipient-email@example.com'

# 慢查询日志文件路径
SLOW_QUERY_LOG_FILE = '/path/to/your/slow-query.log'

# 记录上次读取的位置
last_position = 0

def send_email(subject, body):
    msg = MIMEMultipart()
    msg['From'] = FROM_EMAIL
    msg['To'] = TO_EMAIL
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))
    
    with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
        server.starttls()
        server.login(SMTP_USER, SMTP_PASSWORD)
        server.sendmail(FROM_EMAIL, TO_EMAIL, msg.as_string())

def monitor_slow_query_log():
    global last_position
    with open(SLOW_QUERY_LOG_FILE, 'r') as file:
        file.seek(last_position)
        while True:
            line = file.readline()
            if not line:
                time.sleep(1)  # 等待1秒后再次检查
                continue
            last_position = file.tell()
            if 'Query_time:' in line:
                query_time = float(line.split('Query_time:')[1].split()[0])
                if query_time > 2:  # 假设慢查询时间阈值为2秒
                    slow_query = line.strip()
                    send_email('Slow Query Detected', f'Slow Query: {slow_query}')

if __name__ == '__main__':
    monitor_slow_query_log()

确保你已经安装了所需的Python库(如 smtplib 和 email),然后运行脚本:

7. 运行Python 代码
python 复制代码
python monitor_slow_query_log.py
8. 使用系统工具

如果你不想编写脚本,可以使用一些系统工具来监控文件变化并发送邮件。例如,使用 inotifywait 和 mail 命令:

安装 inotify-tools

在Linux上安装 inotify-tools:

shell 复制代码
sudo apt-get install inotify-tools
9. 创建 monitor_slow_query.sh脚本
shell 复制代码
#!/bin/bash

SLOW_QUERY_LOG_FILE="/path/to/your/slow-query.log"
SMTP_SERVER="smtp.example.com"
SMTP_PORT=587
SMTP_USER="your-email@example.com"
SMTP_PASSWORD="your-email-password"
FROM_EMAIL="your-email@example.com"
TO_EMAIL="recipient-email@example.com"

inotifywait -m -e modify "$SLOW_QUERY_LOG_FILE" |
while read path action file; do
    tail -n 1 "$SLOW_QUERY_LOG_FILE" | grep 'Query_time:' | while read line; do
        query_time=$(echo $line | awk '{print $2}' | cut -d':' -f2)
        if (( $(echo "$query_time > 2" | bc -l) )); then
            echo "Slow Query: $line" | mail -s "Slow Query Detected" -S smtp="$SMTP_SERVER:$SMTP_PORT" -S smtp-auth=login -S smtp-auth-user="$SMTP_USER" -S smtp-auth-password="$SMTP_PASSWORD" -S from="$FROM_EMAIL" "$TO_EMAIL"
        fi
    done
done

执行脚本

shell 复制代码
chmod +x monitor_slow_query.sh
./monitor_slow_query.sh
相关推荐
Habibei1 小时前
Mybatis的分页插件
sql·mybatis
吃汤圆的抹香鲸1 小时前
Rider 安装包 绿色版 Win/Mac/Linux 适合.NET和游戏开发者使用 2025全栈开发终极指南:从零配置到企业级实战
linux·运维·windows·sql·游戏·macos·.net
Mr.pyZhang4 小时前
Android构建系统 - 04 编译产物
android·linux
小王努力学编程7 小时前
【MySQL篇】表的操作
数据库·mysql
汤汤upup7 小时前
面试八股文--数据库基础知识总结(2) MySQL
数据库·mysql·面试
TangKenny7 小时前
information_schema.processlist 表详解
mysql·processlist
m0_7482509310 小时前
mysql数据被误删的恢复方案
数据库·mysql
守城小轩10 小时前
Brave 132 编译指南 Android 篇 - 编译准备:系统要求与推荐工具 (三)
android·chrome·chrome devtools·指纹浏览器·浏览器开发·brave
m0_7482384210 小时前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
一小路一10 小时前
从0-1学习Mysql第五章: 索引与优化
数据库·后端·学习·mysql·面试