1. 业务介绍:
现在有这样一些log文件,文件内容每行一条记录:
-rw-r--r-- 1 root root 3364 6月 26 16:43 face-origin_BACKUP_2013062616.log
-rw-r--r-- 1 root root 1491 6月 26 17:12 face-origin_BACKUP_2013062617.log
-rw-r--r-- 1 root root 3205 6月 27 11:20 face-origin_BACKUP_2013062711.log
-rw-r--r-- 1 root root 7644 6月 27 14:57 face-origin_BACKUP_2013062714.log
-rw-r--r-- 1 root root 2224 6月 27 15:28 face-origin_BACKUP_2013062715.log
-rw-r--r-- 1 root root 26235 6月 27 16:31 face-origin_BACKUP_2013062716.log
-rw-r--r-- 1 root root 6001 6月 30 16:54 face-origin_BACKUP_2013063016.log
-rw-r--r-- 1 root root 25936 7月 1 09:44 faces-origin_BACKUP_2013070109.log
-rw-r--r-- 1 root root 11766 7月 1 10:59 face-origin_BACKUP_2013070110.log
-rw-r--r-- 1 root root 98589 7月 1 11:59 face-origin_BACKUP_2013070111.log
-rw-r--r-- 1 root root 5777 7月 1 14:20 face-origin_BACKUP_2013070114.log
现在业务需要将这些生成的log文件内容分别按照给定的时间读入到数据库零时表中,然后按照内容记录的关键字,将含这些特定关键字的内容插入到一个正式表中。
2. 数据库表结构:
零时表:
CREATE TABLE `total_log_content` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`logcontent` text COMMENT 'log内容',
`logtime` date DEFAULT NULL COMMENT 'log生成日期',
`addtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'log入库日期',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1979 DEFAULT CHARSET=utf8;
正式表(结构同上):
CREATE TABLE `face_ulpos_origin` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`logcontent` text,
`addtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`logtime` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3070 DEFAULT CHARSET=utf8;
3. 实现脚本如下:
#!/bin/bash
export LANG=zh_CN.UTF-8
HOSTNAME="192.168.1.146"
PORT="3306"
USERNAME="username"
PASSWORD="passwd"
DBNAME="LogDB"
log_path='/u1/logs/face-origin'
command="INSERT INTO face_ulpos_origin(logcontent,addtime,logtime) (SELECT logcontent,addtime,logtime FROM total_log_content WHERE logcontent LIKE '%face-ulpos%' AND logcontent LIKE '%consumeHyCard%');"
start_date=$1
end_date=$2
if [ -z $start_date ] || [ -z $end_date ];then
echo "please add two date after the command like './load2db 2013-07-01 2013-07-10'"
exit 1
fi
t1=`date -d $start_date +%s`
t2=`date -d $end_date +%s`
cd $log_path
log_file=`ls *.log`
for i in $log_file
do
filedate=`stat $i | grep Modify | awk '{print $2}'`
t3=`date -d $filedate +%s`
if [[ $t3 -ge $t1 && $t3 -le $t2 ]];then
cp $i $(echo $i|sed 's/\.log/\.txt/')
for j in `ls *.txt`
do
mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e"load data local infile '$log_path/$j' into table total_log_content(logcontent) set logtime='$filedate',addtime = CURRENT_TIMESTAMP;"
rm -rf $j
done
fi
done
mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e"${command}"