MySQL 或 MariaDB 的 Log 記錄檔可以紀錄 MySQL 的錯誤, 對伺服器的除錯很有用, 但這個 MySQL Log 記錄檔跟其他 log 一樣, 不理它會一直增大容量, 而 MySQL 內置沒有記錄檔輪替的功能, 要做記錄檔輪替需要借用其他工具, 可以是自行編寫 Shell Script 或 logrotate, 以下文章會示範在用 logrotate 將 MySQL 的 error log 記錄檔輪替。
第一步需要確定系統有開啟 MySQL Log, 及知道 Log 的位置, 如果在 CentOS 用 yum 安裝 MariaDB, 預設已經開啟記錄檔, 預設記錄檔位置在 “log-error=/var/log/mariadb/mariadb.log”, 如果需要修改這個位置, 或查看系統存放記錄檔的位置, 可以開啟 /etc/my.cnf:
# vi /etc/my.cnf
可以查看裡面的 log-error 位置, 分別在 [mysqld] 及 [mysqld_safe] 段落, 如果沒有可以自行加入, 例如:
1 2 3 4 5 |
[mysqld] log-error=/var/log/mariadb/mariadb.log [mysqld_safe] log-error=/var/log/mariadb/mariadb.log |
如果有修改 my.cnf 的內容, 需要重新啟動 MySQL:
# systemctl restart mysql
現在可以設定 logrotate, 建立檔案 /etc/logrotate.d/mysql:
# vi /etc/logrotate.d/mysql
以下的設定以上面的記錄檔位置 /var/log/mariadb/mariadb.log 作為例子:
另外如果不是用 RHEL 及 CentOS, 可能有些參數要按系統的配置進行修改, 加入以下內容到檔案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/var/log/mariadb/mariadb.log { create 600 mysql mysql notifempty daily maxsize 100M ## 當記錄檔超過 100MB 時輸替 dateext rotate 5 missingok compress delaycompress postrotate # just if mysqld is really running if test -x /usr/bin/mysqladmin && \ /usr/bin/mysqladmin ping &>/dev/null then echo "Flushing Logs" /usr/bin/mysqladmin flush-logs fi endscript } |
儲存檔案後離開 vi, logrotate 便設定完成了。