Configuring Logrotate for MySQL on Linux: Automatically Rotate Error and Slow Query Logs to Prevent Full Disks

MySQL tutorial - IT technology blog
MySQL tutorial - IT technology blog

Early in my career, I ran into an unforgettable incident on a production server. The website suddenly started throwing database connection errors left and right, even though CPU and RAM usage were still under 40%. After SSHing in and running df -h, I was shocked to see that the 50 GB /var partition had hit 100% capacity. The culprit wasn’t a sudden spike in table data, but MySQL’s Error Log and Slow Query Log files ballooning to over 38 GB.

The root cause went back a few months earlier: When the users table exceeded 10 million rows, I started seeing slow queries and had to optimize the indexes. Wanting to catch every sluggish query, I lowered long_query_time to 0.5 seconds. I turned on logging and completely forgot to set up log rotation and cleanup for old files. After just one traffic surge, the disk filled up before I knew it.

Three Common Ways to Rotate MySQL Logs on Linux

To keep MySQL log sizes under control, developers and sysadmins typically choose one of these three approaches:

  • Custom Bash script + Cronjob: Write a script to copy the log to a new file, empty the original file with truncate or > file.log, and schedule it via crontab.
  • Logrotate + mysqladmin flush-logs: Leverage the built-in logrotate utility on Ubuntu, Debian, or RHEL/Rocky Linux to automatically split, compress, and prune old logs while signaling MySQL to open a fresh log file.
  • Centralized log shipping: Use Fluent Bit, Filebeat, or rsyslog to ship logs to an external server (such as ELK or Grafana Loki) while capping local disk retention.

Pros and Cons of Each Approach

1. Custom Bash Script and Cronjob

At first glance, this looks neat because it only takes a few lines of shell script to get up and running.

  • Pros: No extra tools needed, and you have full control to write whatever custom logic you want.
  • Cons: It is very easy to fall into OS-level traps. If you use rm or mv while MySQL is running without flushing, the mysqld process keeps holding the file descriptor pointing to the old inode. The file disappears from the directory, yet df -h still reports the disk as full until you restart MySQL (you can verify this with lsof | grep deleted). On the other hand, if you use cp followed by truncate, any log lines written in the split second between those two commands are lost forever.

2. Logrotate Combined with mysqladmin flush-logs

This is the standard Linux tool for managing the lifecycle of system log files.

  • Pros: Reliable and lightweight. Logrotate natively supports gzip compression, retaining an exact number of recent backups, skipping empty files, and creating new files with the proper mysql ownership. Most importantly, its postrotate hook safely invokes FLUSH LOGS without interrupting database operations.
  • Cons: You must configure MySQL credentials properly for the background script. If permissions on the credential file are too permissive, other users on the server could read the password.

3. Shipping Logs to a Centralized System

  • Pros: Very convenient when managing a cluster of 5–10+ servers and needing centralized log search without SSHing into individual machines.
  • Cons: Consumes extra RAM and CPU for the log agent (around 100–300 MB of RAM) plus the cost of running a log storage server. For a single VPS or standalone server, this setup is overkill.

Which Approach Should You Choose for Your Server?

If you are running MySQL on a VPS, EC2 instance, or small-to-medium production server, go straight for Logrotate + mysqladmin flush-logs. It prevents dropping in-flight logs, avoids restarting MySQL, and uses virtually zero extra system resources.

Step-by-Step Guide to Configuring Logrotate for MySQL

The steps below are demonstrated on Ubuntu/Debian. If you are on RHEL, CentOS, or Rocky Linux, the process is nearly identical—only the default log directory path differs (usually /var/log/mysqld.log).

Step 1: Locate Your Error Log and Slow Query Log Paths

First, ask MySQL directly where it is currently writing its logs by running:

mysql -u root -p -e "SHOW VARIABLES WHERE Variable_name IN ('log_error', 'slow_query_log', 'slow_query_log_file');"

On Ubuntu, these two files are typically located at /var/log/mysql/error.log and /var/log/mysql/mysql-slow.log. Check their current sizes and ownership:

ls -lh /var/log/mysql/

Take note of the user and group columns (usually mysql adm or mysql mysql) so you can match them in your configuration file later.

Step 2: Create a Dedicated Authentication File for mysqladmin

Never hardcode your MySQL password directly inside /etc/logrotate.d/, as other system users may have read access to that directory. Instead, create a dedicated configuration file at /etc/mysql/logrotate.cnf and restrict read permissions to root only:

sudo tee /etc/mysql/logrotate.cnf > /dev/null <<'EOF'
[client]
user=logrotate_user
password=YourStrongPassword123!
EOF
sudo chmod 600 /etc/mysql/logrotate.cnf

In MySQL, create a dedicated user and grant only the minimum RELOAD privilege (just enough to run flush-logs, with no permission to read or modify data):

mysql -u root -p -e "CREATE USER IF NOT EXISTS 'logrotate_user'@'localhost' IDENTIFIED BY 'YourStrongPassword123!'; GRANT RELOAD ON *.* TO 'logrotate_user'@'localhost'; FLUSH PRIVILEGES;"

Quick tip for Ubuntu: if your server uses auth_socket for the Linux root user, try running sudo mysqladmin flush-logs to see if it works out of the box. If it succeeds, you can skip creating logrotate_user and omit the --defaults-extra-file flag in the next step.

Step 3: Create the Logrotate Configuration File for MySQL

Check /etc/logrotate.d/ to see if your MySQL package already created a mysql-server file. If not, or if you prefer a separate file for easier management, create /etc/logrotate.d/mysql-logs as follows:

sudo tee /etc/logrotate.d/mysql-logs > /dev/null <<'EOF'
/var/log/mysql/error.log /var/log/mysql/mysql-slow.log {
    su mysql adm
    daily
    rotate 14
    missingok
    notifempty
    compress
    delaycompress
    create 640 mysql adm
    sharedscripts
    postrotate
        if test -x /usr/bin/mysqladmin && \
           /usr/bin/mysqladmin --defaults-extra-file=/etc/mysql/logrotate.cnf ping &>/dev/null
        then
            /usr/bin/mysqladmin --defaults-extra-file=/etc/mysql/logrotate.cnf flush-logs
        fi
    endscript
}
EOF

Here is a quick breakdown of the key directives above:

  • su mysql adm: Specifies the user and group used to perform rotation. Without this line when /var/log/mysql is owned by mysql:adm, modern versions of logrotate will refuse to run for security reasons.
  • daily & rotate 14: Rotates logs once a day and keeps up to 14 old archives (2 weeks). If your logs grow very quickly, you can add maxsize 500M, though keep in mind that logrotate’s default systemd timer or cron job only runs once daily.
  • missingok & notifempty: Avoids throwing an error if a log file does not exist yet, and skips rotation if the file is 0 bytes.
  • compress & delaycompress: Compresses rotated files into .gz format, saving 80–90% of disk space (a 1 GB file shrinks to around 100–150 MB). Adding delaycompress postpones compression until the next rotation cycle to prevent conflicts while MySQL is still finishing its flush.
  • create 640 mysql adm: Immediately creates a new log file with 640 permissions (change this to mysql mysql if Step 1 showed the group as mysql).
  • sharedscripts: Ensures the postrotate block runs only once for both files instead of calling flush-logs twice. Note that if Binary Logging (log_bin) is enabled, mysqladmin flush-logs will also rotate to a new binlog file.

Step 4: Test with a Dry-Run

Never edit a production configuration and call it a day without testing. Run a dry-run using the -d (debug) flag to preview what logrotate will do without touching any actual files:

sudo logrotate -d /etc/logrotate.d/mysql-logs

Carefully inspect the output for any permission errors or incorrect paths. Once everything looks clean, force an actual rotation once using the -f (force) flag:

sudo logrotate -f /etc/logrotate.d/mysql-logs

Step 5: Verify the Results

Check the log directory to confirm the old file has been renamed to .1 (it will be compressed to .2.gz on the next run) and that the new file has the right permissions:

ls -lh /var/log/mysql/

Finally, trigger a test slow query to verify everything works in practice. If long_query_time is set to 2 seconds, run SELECT SLEEP(3); (or SELECT SLEEP(11); if it’s at the 10-second default), then check whether the entry appears in the newly created mysql-slow.log file. Once you see logs writing normally, MySQL has cleanly switched to the new file descriptor—and you can sleep easy without worrying about midnight disk-full alerts.

Share: