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 = '[email protected]'
SMTP_PASSWORD = 'your-email-password'
FROM_EMAIL = '[email protected]'
TO_EMAIL = '[email protected]'

# 慢查询日志文件路径
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="[email protected]"
SMTP_PASSWORD="your-email-password"
FROM_EMAIL="[email protected]"
TO_EMAIL="[email protected]"

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
相关推荐
CYRUS_STUDIO3 小时前
FART 脱壳某大厂 App + CodeItem 修复 dex + 反编译还原源码
android·安全·逆向
青春之我_XP4 小时前
【基于阿里云搭建数据仓库(离线)】Data Studio创建资源与函数
大数据·数据仓库·sql·dataworks·maxcompute·data studio
Snk0xHeart5 小时前
极客大挑战 2019 EasySQL 1(万能账号密码,SQL注入,HackBar)
数据库·sql·网络安全
Shujie_L5 小时前
【Android基础回顾】四:ServiceManager
android
Think Spatial 空间思维6 小时前
【实施指南】Android客户端HTTPS双向认证实施指南
android·网络协议·https·ssl
天天摸鱼的java工程师6 小时前
高考放榜夜,系统别崩!聊聊查分系统怎么设计,三张表足以?
java·后端·mysql
louisgeek6 小时前
Git 使用 SSH 连接
android
二流小码农6 小时前
鸿蒙开发:实现一个标题栏吸顶
android·ios·harmonyos
exe4527 小时前
jdbc查询mysql数据库时,出现id顺序错误的情况
数据库·mysql
八月林城7 小时前
echarts在uniapp中使用安卓真机运行时无法显示的问题
android·uni-app·echarts