How to Use Bash Script for MySQL Error Log Rotation

How to Use Bash Script for MySQL Error Log Rotation

We will share with you a script that we can use to find the solution and the solution that we receive in the Mysql database.

Below is the simple script for monitoring MySQL error logs. You can set the cron jobs as per your need(eg. week, daily, hourly)

#!/bin/bash
SERNAME="techsoftcenter"
SERPUBIP="10.0.0.0"
SERVER="ip-10.0.0.0"
 
MAIL_LIST="[email protected]"
Error_log_location=/var/log
Alert_log_path=/opt/work/dblogs
 
sudo egrep -i 'Error' $Error_log_location/mysqld.log |sort -u > $Alert_log_path/mysqld_ALERTLOG.txt
 
if [ $? -eq 0 ]; then
sudo cat $Error_log_location/mysqld.log > $Alert_log_path/mysqld_archived_`date +%Y-%m-%d-%H:%M:%S`.log
 
if [ $? -eq 0 ]; then
 
sudo cat /dev/null > $Error_log_location/mysqld.log
 
else
 
echo "failed to empty file"
 
fi
 
else
 
echo "something went wrong after log file backup"
 
fi
 
cd /tmp/
cd /opt/work/dblogs/
 
FILE_TYPE="*.txt"
FILE_TYPE1="*.log"
 
find ${FILE_TYPE} -type f -mtime +1 -delete
find ${FILE_TYPE1} -type f -mtime +1 -delete
 
if [ -s "$Alert_log_path/mysqld_ALERTLOG.txt" ] ; then
cat $Alert_log_path/mysqld_ALERTLOG.txt | mutt -s "URGENT -ERROR in Mysql Alert Log File for $SERNAME ($SERPUBIP) at `date` " -- ${MAIL_LIST}
fi

Hope it helped.