实现原理
先另存mysql_general日志文件,然后创建新的mysql_general文件,再通过mysql自带的 flush-logs general 刷新general日志,同时把历史日志进行压缩保存在mysql_log_his目录下.如需定期删除,可自行添加删除命令
准备事项
#先创建general日志文件
touch /www/logs/mysql_general.log
chown mysql:mysql /www/logs/mysql_general.log
#动态开启general日志 mysql终端执行
set global general_log_file='/www/logs/mysql_general.log';
set global general_log="ON";
#修改日志文件里面的时区,改成跟系统一致
set global log_timestamps=SYSTEM;
#增加flush日志用的账号及权限
GRANT reload ON *.* TO 'backup'@'localhost' identified by '密码';
#my.cnf配置文件同步增加如下内容,防止后期重启mysql后配置丢失
log_timestamps=SYSTEM
general_log = on
general_log_file = /www/logs/mysql_general.log
自动裁剪脚本
vi /www/cron/mysql_general_cut.sh
#!/bin/bash
#mysql的查询日志按天裁剪脚本, mysql路径按需自行调整
#0 0 * * * root /bin/sh /www/cron/mysql_general_cut.sh >> /www/task/backup_db.log
#执行的用户需要有reload的权限
#GRANT reload ON *.* TO 'backup'@'localhost' identified by '密码';
GENERAL_LOG=/www/logs/mysql_general.log
GENERAL_HIS=/www/logs/mysql_log_his/
if [ ! -d $GENERAL_HIS ];then
mkdir -p $GENERAL_HIS
fi
if [ -f $GENERAL_LOG ]; then
mv $GENERAL_LOG $GENERAL_HIS/mysql_general_$(date -d "yesterday" +"%Y%m%d").log
touch $GENERAL_LOG
chown mysql:mysql $GENERAL_LOG
/usr/local/webserver/mysql/bin/mysqladmin --defaults-file=/www/cron/mysqluse flush-logs general
cd $GENERAL_HIS
tar -zcvf mysql_general_$(date -d "yesterday" +"%Y%m%d").tar.gz mysql_general_$(date -d "yesterday" +"%Y%m%d").log --remove-files
fi
exit
mysql用户账号配置,用于mysql_general_cut.sh脚本内用户
vi /www/cron/mysqluse
[client]
user=root
password="xxxx"
#如果用socket连接的话,需要指定sock文件
#socket = /tmp/mysql3306.sock
添加定时任务
vi /etc/crontab
0 0 * * * root /bin/sh /www/cron/mysql_general_cut.sh >> /www/task/backup_db.log
本文由博客一文多发平台 OpenWrite 发布!