mysql清理日誌

月夜原野發表於2017-10-16

轉自:http://coolnull.com/154.html


說明:
當開啟mysql資料庫主從時,會產生大量如mysql-bin.00000* log的檔案,這會大量耗費您的硬碟空間。
mysql-bin.000001
mysql-bin.000002
mysql-bin.000003
mysql-bin.000004
mysql-bin.000005

有三種解決方法:1.關閉mysql主從,關閉binlog;2.開啟mysql主從,設定expire_logs_days;3.手動清除binlog檔案,> PURGE MASTER LOGS TO ‘MySQL-bin.010’;

實現:
1.關閉mysql主從,關閉binlog

# vim /etc/my.cnf  //註釋掉log-bin,binlog_format
# Replication Master Server (default)
# binary logging is required for replication
# log-bin=mysql-bin
# binary logging format - mixed recommended
# binlog_format=mixed

然後重啟資料庫

2.重啟mysql,開啟mysql主從,設定expire_logs_days

# vim /etc/my.cnf  //修改expire_logs_days,x是自動刪除的天數,一般將x設定為短點,如10
expire_logs_days = x  //二進位制日誌自動刪除的天數。預設值為0,表示“沒有自動刪除”

此方法需要重啟mysql,附錄有關於expire_logs_days的英文說明

當然也可以不重啟mysql,開啟mysql主從,直接在mysql裡設定expire_logs_days

> show binary logs;
> show variables like '%log%';
> set global expire_logs_days = 10;

 
3.手動清除binlog檔案

# /usr/local/mysql/bin/mysql -u root -p
> PURGE MASTER LOGS BEFORE DATE_SUB(CURRENT_DATE, INTERVAL 10 DAY);   //刪除10天前的MySQL binlog日誌,附錄2有關於PURGE MASTER LOGS手動刪除用法及示例
> show master logs;

 
也可以重置master,刪除所有binlog檔案:

# /usr/local/mysql/bin/mysql -u root -p
> reset master;  //附錄3有清除binlog時,對從mysql的影響說明

 
附錄:
1.expire_logs_days英文說明
Where X is the number of days you’d like to keep them around. I would recommend 10, but this depends on how busy your MySQL server is and how fast these log files grow. Just make sure it is longer than the slowest slave takes to replicate the data from your master.
Just a side note: You know that you should do this anyway, but make sure you back up your mysql database. The binary log can be used to recover the database in certain situations; so having a backup ensures that if your database server does crash, you will be able to recover the data.

2.PURGE MASTER LOGS手動刪除用法及示例,MASTER和BINARY是同義詞

> PURGE {MASTER | BINARY} LOGS TO 'log_name'
> PURGE {MASTER | BINARY} LOGS BEFORE 'date'

刪除指定的日誌或日期之前的日誌索引中的所有二進位制日誌。這些日誌也會從記錄在日誌索引檔案中的清單中被刪除MySQL BIN-LOG 日誌,這樣被給定的日誌成為第一個。

例項:

> PURGE MASTER LOGS TO 'MySQL-bin.010';  //清除MySQL-bin.010日誌
> PURGE MASTER LOGS BEFORE '2008-06-22 13:00:00';   //清除2008-06-22 13:00:00前binlog日誌
> PURGE MASTER LOGS BEFORE DATE_SUB( NOW( ), INTERVAL 3 DAY);  //清除3天前binlog日誌BEFORE,變數的date自變數可以為'YYYY-MM-DD hh:mm:ss'格式。

 
3.清除binlog時,對從mysql的影響
如果您有一個活性的從屬伺服器,該伺服器當前正在讀取您正在試圖刪除的日誌之一,則本語句不會起作用,而是會失敗,並伴隨一個錯誤。不過,如果從屬伺服器是休止的,並且您碰巧清理了其想要讀取的日誌之一,則從屬伺服器啟動後不能複製。當從屬伺服器正在複製時,本語句可以安全執行。您不需要停止它們。

相關文章