#!/bin/bash set -e logFile="/var/log/mysql/error.log" dateFile="/tmp/mysql_scheduler_log-lastdate" logSchema="util" logTable="eventLog" pattern='^\d{4}-\d{2}-\d{2}\s+\d{1,2}:\d{2}:\d{2}\s+\d+\s+\[ERROR\] Event Scheduler:' purgeDays=30 quote() { local str=${1//\'/\'\'/} local str=${str//\\/\\\\} echo "'$str'" } mysql -e "SELECT TRUE" > /dev/null 2>&1 if [ "$?" -ne "0" ]; then exit fi tableExists=$(mysql -Ns -e "SHOW TABLES FROM $logSchema LIKE '$logTable'") if [ -z "$tableExists" ]; then mysql <<-EOF CREATE SCHEMA IF NOT EXISTS $logSchema; CREATE TABLE $logSchema.$logTable ( id int(11) NOT NULL AUTO_INCREMENT, date datetime NOT NULL, event varchar(512) NOT NULL, error varchar(1024) NOT NULL, PRIMARY KEY (id), KEY date (date) ) ENGINE=InnoDB COMMENT='Event scheduler error log'; EOF fi if [ -f "$dateFile" ]; then read -r fromDate < "$dateFile" else fromDate=$(date -d "-$purgeDays days" +%s) fi toDate=$(date +%s) grep -P "$pattern" "$logFile" | awk -v fromDate="$fromDate" -v toDate="$toDate" '{ split($1, date, "-"); split($2, time, ":"); timestamp = mktime(date[1]" "date[2]" "date[3]" "time[1]" "time[2]" "time[3]) if (timestamp >= fromDate && timestamp < toDate) { printf $1" "$2" "$7; for (i=8; i<=NF; i++) printf FS $i ; print ""; } }' | \ while read line; do date="$(echo "$line" | cut -d' ' -f1,2)" event="$(echo "$line" | cut -d' ' -f3)" error="$(echo "$line" | cut -d' ' -f4-)" mysql <<-EOF INSERT INTO $logSchema.$logTable SET date = $(quote "$date"), event = $(quote "$event"), error = $(quote "$error") EOF done echo "$toDate" > "$dateFile" mysql <<-EOF DELETE FROM $logSchema.$logTable WHERE date < TIMESTAMPADD(DAY, -$purgeDays, NOW()) EOF