vn-ansible/roles/db/files/scripts/scheduler-log.sh

74 lines
1.7 KiB
Bash
Raw Normal View History

2025-02-04 08:30:12 +00:00
#!/bin/bash
set -e
logFile="/var/log/mysql/error.log"
dateFile="/tmp/mysql_scheduler_log-lastdate"
logSchema="util"
logTable="eventLog"
2025-02-07 13:25:31 +00:00
pattern='^\d{4}-\d{2}-\d{2}\s+\d{1,2}:\d{2}:\d{2}\s+\d+\s+\[ERROR\] Event Scheduler:'
2025-02-04 08:30:12 +00:00
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
2025-02-04 08:30:12 +00:00
if [ -f "$dateFile" ]; then
read -r fromDate < "$dateFile"
2025-02-04 08:30:12 +00:00
else
fromDate=$(date -d "-$purgeDays days" +%s)
2025-02-04 08:30:12 +00:00
fi
toDate=$(date +%s)
2025-02-04 08:30:12 +00:00
grep -P "$pattern" "$logFile" | awk -v fromDate="$fromDate" -v toDate="$toDate" '{
2025-02-04 08:30:12 +00:00
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) {
2025-02-04 08:30:12 +00:00
printf $1" "$2" "$7;
for (i=8; i<=NF; i++) printf FS $i ;
print "";
}
}' | \
2025-02-04 08:30:12 +00:00
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
2025-02-04 08:30:12 +00:00
done
echo "$toDate" > "$dateFile"
mysql <<-EOF
DELETE FROM $logSchema.$logTable
WHERE date < TIMESTAMPADD(DAY, -$purgeDays, NOW())
EOF