Automatically purging binary logs

Seems like expire_logs_days 7 would be a lot simpler.

8.0 is moving toward binlog_expire_logs_seconds.


I have yet another method for automatically purging logs on master based on what a slave has replicated.

Disclaimer: I haven't had this solution in production for very long, so proceed at your own risk

The following shell script should be run on the master server. It assumes that the slave can be accessed via SSH. You could easily adapt this to other scenarios.

#!/bin/bash

# This script assumes you have configured mysql to run without asking for username/password
# on both the master and slave hosts. (e.g. by putting credentials in ~/.my.cnf)

# Replace 'replication-server' with the hostname of your slave server.
SECONDS=$(echo 'SHOW SLAVE STATUS\G' | ssh replication-server mysql | grep Seconds_Behind_Master | grep -o '[0-9]\+' )

# This performs the actual purge on the Master DB
# It calculates what date the slave has replicated to, and then subtracts an additional 1 week
# buffer just in case.
echo "PURGE BINARY LOGS BEFORE DATE(NOW() - INTERVAL 1 WEEK - INTERVAL $SECONDS SECOND)" | mysql

I run this script on a daily cron schedule to ensure logs are purged regularly.

Tags:

Mysql