Ok. So I just looked at two blog posts about MySQL log rotation. While not technically incorrect, I'd like to disagree with the final answer, mainly because recreating the wheel drives me crazy.
Rather than writing a custom script to do this and putting that script in cron, why not use logrotate?
We already ship fully functional log rotate scripts in the Debian MySQL packages. Here's an example:
Now, if you aren't on Debian, don't just copy this verbatim, as you probably don't have a debian-sys-maint user or an /etc/mysql/debian.cnf file. In Debian, we make this at package install time and refresh it on upgrades. It's a system user with an autogenerated password put in a file only readable by root, that allows system scripts like this to run unattended.
Once you read up a little on logrotate, you'll realize it's really great at just about anything you need to do in the log rotation field. Have fun!
Rather than writing a custom script to do this and putting that script in cron, why not use logrotate?
We already ship fully functional log rotate scripts in the Debian MySQL packages. Here's an example:
/var/log/mysql.log /var/log/mysql/mysql.log /var/log/mysql/mysql-slow.log {
daily
rotate 7
missingok
create 640 mysql adm
compress
sharedscripts
postrotate
test -x /usr/bin/mysqladmin || exit 0
# If this fails, check debian.conf!
export HOME=/etc/mysql/my.cnf
MYADMIN="/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf"
if [ -z "`$MYADMIN ping 2>/dev/null`" ]; then
# Really no mysqld or rather a missing debian-sys-maint user?
# If this occurs and is not a error please report a bug.
if ps cax | grep -q mysqld; then
exit 1
fi
else
$MYADMIN flush-logs
fi
endscript
}
This does the re-creation, flush logs and handles failure conditions gracefully. It also compresses old files. Even better - your system already has logrotate running (unless you run a really bad distro)Now, if you aren't on Debian, don't just copy this verbatim, as you probably don't have a debian-sys-maint user or an /etc/mysql/debian.cnf file. In Debian, we make this at package install time and refresh it on upgrades. It's a system user with an autogenerated password put in a file only readable by root, that allows system scripts like this to run unattended.
Once you read up a little on logrotate, you'll realize it's really great at just about anything you need to do in the log rotation field. Have fun!
0 Comments