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
相关推荐
coderlin_2 小时前
BI布局拖拽 (1) 深入react-gird-layout源码
android·javascript·react.js
sun0077002 小时前
mysql索引底层原理
数据库·mysql
2501_915918412 小时前
Fiddler中文版全面评测:功能亮点、使用场景与中文网资源整合指南
android·ios·小程序·https·uni-app·iphone·webview
程序员秘密基地3 小时前
基于html,css,vue,vscode,idea,,java,springboot,mysql数据库,在线旅游,景点管理系统
java·spring boot·mysql·spring·web3
wen's4 小时前
React Native安卓刘海屏适配终极方案:仅需修改 AndroidManifest.xml!
android·xml·react native
编程乐学5 小时前
网络资源模板--基于Android Studio 实现的聊天App
android·android studio·大作业·移动端开发·安卓移动开发·聊天app
叁沐5 小时前
MySQL 11 怎么给字符串字段加索引?
mysql
没有了遇见7 小时前
Android 通过 SO 库安全存储敏感数据,解决接口劫持问题
android
hsx6667 小时前
使用一个 RecyclerView 构建复杂多类型布局
android
hsx6667 小时前
利用 onMeasure、onLayout、onDraw 创建自定义 View
android