本文共 1487 字,大约阅读时间需要 4 分钟。
随着业务规模的扩大和时间的推移,MySQL的日志文件必然会呈指数级增长,日志文件的体积也会不断膨胀。为了有效管理这些日志文件,通常需要使用logrotate进行轮替管理。MySQL官方提供的二进制包中包含了用于日志轮转的logrotate脚本,位于support-files
文件夹中,文件名为mysql-log-rotate
。不过,这个脚本需要经过适当修改后才能正常使用。
以下是修改后的MySQL日志轮转脚本内容:
#!/bin/sh## This logname can be set in /etc/my.cnf by setting the variable "err-log"# in the [safe_mysqld] section as follows:## [safe_mysqld]## err-log=/usr/local/mysql/data/mysqld.log## If the root user has a password, you need to create a# /root/.my.cnf configuration file with the following content:## [mysqladmin]## user = root## password = ### host = yourhost## port = 3307# ## This ensures that /root/.my.cnf is only readable by root.#{ create 600 mysql mysql \ -- notifies missingok daily rotate 3 compress postrotate { if test -x /usr/local/mysql/bin/mysqladmin \ && /usr/local/mysql/bin/mysqladmin ping > /dev/null \ then /usr/local/mysql/bin/mysqladmin flush-logs fi }}
将修改后的logrotate脚本复制到/etc/logrotate.d/mysqld
文件中。需要注意的是,如果你的MySQL根用户设置了密码,你需要在/root/.my.cnf
文件中添加相应的配置信息,以便mysqladmin能够正常使用。
在/root/.my.cnf
文件中添加以下内容:
[root@localhost ~]# vim .my.cnf[root@localhost ~]#[mysqladmin] user = root password = host = yourhost port = 3307
请将<secret>
部分中的内容替换为你的实际密码信息。这样配置后,logrotate脚本就可以正常地执行日志轮转操作了。
需要注意的是,如果日志文件为空,logrotate会自动忽略该操作。日志轮转操作每天执行3次,并且如果发现MySQL服务未启动,会自动调用flush-logs
命令完成日志刷新。
通过以上方法,你可以轻松地实现MySQL日志的自动轮转管理,避免日志文件占用过多存储空间,并确保服务器运行更加稳定。
转载地址:http://wvdfk.baihongyu.com/