mysqlのログをlogrotateする

mysqlのログローテートで少しはまったのでメモしておきます。
mysqlではサーバーのエラーログの他にクエリーログやスロークエリーログなどがあり、これらを一日一回logrotateを用いてローテーションさせたいと思いました。

CentOSには /etc/logrotate.d/mysqld が用意されており、内容を確認すると、

# cat /etc/logrotate.d/mysqld
# 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=/var/log/mysqld.log
#
# If the root user has a password you have to create a
# /root/.my.cnf configuration file with the following
# content:
#
# [mysqladmin]
# password = <secret>
# user= root
#
# where "<secret>" is the password.
#
# ATTENTION: This /root/.my.cnf should be readable ONLY
# for root !
# Then, un-comment the following lines to enable rotation of mysql's log file:
以下略

のように記載がありましたので、その通り実行しました。

まず、mysqladminを用いてflush-logsコマンドを実行するための専用ユーザー(reload)を作成します。

$ mysql -u root -p mysql
> GRANT RELOAD ON *.* TO 'reload'@'localhost' IDENTIFIED BY 'password';

次に、そのユーザーの情報を/root/.my.cnfに記載します。

# cat - > /root/.my.cnf
[mysqladmin]
user=reload
password=<secret>
^C
# chmod 600 /root/.my.cnf

最後に、/etc/logrotate.d/mysqld に次のように記載します。
(保存ファイル数などは目的に合わせて変更してください)

/var/log/mysql/mysqld.log /var/log/mysql/slow.log /var/log/mysql/query.log {
    daily
    missingok
    rotate 4
    compress
    delaycompress
    notifempty
    create 640 mysql mysql
    sharedscripts
    postrotate
        # just if mysqld is really running
        if test -x /usr/bin/mysqladmin && \
            /usr/bin/mysqladmin ping &>/dev/null
        then
            env HOME=/root/ /usr/bin/mysqladmin flush-logs
        fi
    endscript
}

重要なのは

env HOME=/root/ /usr/bin/mysqladmin flush-logs

この部分で、パッケージインストール時点で用意されていたファイルには
env HOME=/root/
の記述がありませんでした。
logrotateはanacronから起動されるのですが、anacronは /etc/cron.d/0hourlyに記載された内容に従って、cronが/etc/cron.hourly/0anacronを読み込んで実行されます。
しかし、ここで /etc/cron.d/0hourly に

# cat /etc/cron.d/0hourly
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
01 * * * * root run-parts /etc/cron.hourly

HOME=/の記述があるために、rootユーザーのHOMEが/と認識されてしまいます。
/直下に.my.cnfを置くことでも対応可能でしょうが、上記のようにenvコマンドを用いることで対応できますので、今回はこのように記載しました。