MySQLのlogrotate設定

cronで動かした時だけログがフラッシュされなかったりとハマったわ…。

まずlogrotateの設定
コメントされてはいるものの、もともと内容が書いてあるが、
スロークエリログなどもローテーションしたいので少し書き換えて以下の様にした。

# vi /etc/logrotate.d/mysql
# 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 =
# user= root
#
# where "" 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:

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

コメントに書いてある通り、/root/.my.cnfを作成してmysqladminがパスなしでも動作する様にする。

# vi /root/.my.cnf
[mysqladmin]
user=root
password=パスワード
# chmod 600 /root/.my.cnf

やらなくてもいいけど、うまく動作しない理由を知りたかったので
logrotateの出力を見れる様にした。

# vi /etc/cron.daily/logrotate
#!/bin/sh

/usr/sbin/logrotate -v /etc/logrotate.conf >/var/log/logrotate 2>&1
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
/usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0

  • vオプションつけて、標準出力の内容を/var/log/logrotateに書き込む様にした。

ハマってた時にこのログを見ると、mysqladminで「error: 'Access denied for user 'root'@'localhost' (using password: NO)'」
が出ていて、
手動でlogrotate -f /etc/logrotate.confするとflush-logs実行されるのに何でcronだとダメなのかまったくわからなかったが、
それは↓のが原因だった。

cron.d/dailyjobsのHOMEを修正する。

# vi /etc/cron.d/dailyjobs
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/root/ ←コレ!!!!コレが/になってたら/root/に直す!!
/etc/crontabを変えても反映されないので注意。

これで毎日ログがフラッシュされる様になった。