通用查詢日誌可記錄客戶端連接、斷開及所有執行的 SQL 語句,是審計、排查注入、性能分析的重要手段。本文介紹開啟方法與管理策略。
# /etc/my.cnf
[mysqld]
# 啟用通用查詢日誌
general_log = 1
# 日誌文件路徑(確保 mysql 用戶有寫權限)
general_log_file = /var/lib/mysql/sql_audit.log
# 可選:同時輸出到表(mysql.general_log),便於 SQL 查詢分析
log_output = FILE,TABLE
systemctl restart mysqld
# 或
service mysqld restart
-- 開啟
SET GLOBAL general_log = ON;
SET GLOBAL general_log_file = '/var/lib/mysql/sql_audit.log';
-- 關閉
SET GLOBAL general_log = OFF;
/usr/sbin/mysqld, Version: 8.0.33 (MySQL Community Server). started with:
Tcp port: 3306 Unix socket: /var/lib/mysql/mysql.sock
Time Id Command Argument
2024-01-15T10:30:01 10 Connect root@localhost on test_db
2024-01-15T10:30:02 10 Query SELECT * FROM users WHERE id = 1
2024-01-15T10:30:05 10 Query INSERT INTO logs (msg) VALUES ('test')
2024-01-15T10:30:10 10 Quit
-- 查看最近 100 條記錄
SELECT event_time, user_host, thread_id, command_type, argument
FROM mysql.general_log
ORDER BY event_time DESC LIMIT 100;
-- 統計高頻 SQL
SELECT argument, COUNT(*) AS cnt
FROM mysql.general_log
WHERE command_type = 'Query'
GROUP BY argument
ORDER BY cnt DESC LIMIT 20;
log_output = TABLE 定期清理 mysql.general_log 表# /etc/logrotate.d/mysql-general
/var/lib/mysql/sql_audit.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 640 mysql mysql
sharedscripts
postrotate
mysqladmin flush-logs -u root -pPASSWORD 2>/dev/null || true
endscript
}
| 方案 | 開銷 | 功能 | 適用場景 |
|---|---|---|---|
| General Log | 高 | 全量 SQL、連接事件 | 臨時排查、審計 |
| Slow Query Log | 低 | 慢查詢、未使用索引 | 長期開啟、性能優化 |
| Binary Log | 中 | DDL/DML 變更、複製、PITR | 主從複製、數據恢復 |
| Audit Plugin | 低-中 | 可過濾、標準格式、合規 | 生產長期審計、合規要求 |