MySQL log retention policy: set binlog log storage days, file size limit


1. Set binlog log storage days and file size limit

In MySQL, there are three main types of logging: binary logs (binlog), error logs, and query logs. These log records are very important for the administration and maintenance of the MySQL database. In this article, we will focus on how to set the retention policy for binlog logs.

By default, MySQL will automatically save binlog log files in the main directory or a specified directory, and there is no limit to the size of binlog log files and log retention time. This means that you need to manually delete the log files when they get too large or when you no longer need them.

Therefore, in order to optimize the management of the MySQL database, we can set the retention policy of the binlog log by adding the following content to the MySQL configuration file my.cnf:

[mysqld]
#设置日志保留天数
expire_logs_days=7
#设置日志文件最大大小
max_binlog_size=100M

The above configuration will keep the binlog log files of the last 7 days, and the maximum size of each binlog file is 100M. When the total size of binlog log files exceeds 100M, MySQL will automatically create a new binlog log file. After more than 7 days, MySQL will automatically delete all old binlog log files.

After changing the settings, the MySQL service needs to be restarted for it to take effect.

Notice:

  • The maximum value of the log file cannot be set to less than 4096 bytes.
  • If you use "log_bin_trust_function_creators=1", the MySQL version will ignore "binlog_format = STATEMENT", that is, only ROW mode and MIXED mode are supported.

2. How to manually clean up the binlog

1. Using the MySQL command line

On the MySQL command line, use the PURGE BINARY LOGS statement to delete all expired binlog log files created before the specified date.

For example, to delete binlog log files older than 7 days, run the following command:

PURGE BINARY LOGS BEFORE DATE_SUB(NOW(), INTERVAL 7 DAY);

2. Delete according to the binlog name

## 将mysql-bin.000011之前的日志清理掉
mysql> purge binary logs to 'mysql-bin.000011';
Query OK, 0 rows affected (0.01 sec)

3. Delete according to time

## 删除2023-03-21 18:08:00之前的binlog日志
mysql> purge binary logs before '2023-03-21 18:08:00';
Query OK, 0 rows affected, 1 warning (0.02 sec)

Tip: For more content, please visit Clang's Blog: https://www.clang.asia

Guess you like

Origin blog.csdn.net/u012899618/article/details/129790336