shell脚本日志收集与打包 Posted on 2016-12-26 线上日志收集是很正常的业务,一般由运营来处理,现在给一段代码来实现日志的收集,打包以及上传到s3备份存储,请看代码:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146#!/bin/shfunction send_sms(){ . /data/se_scripts/conf/setting_new.conf phone=$phone_number phone=$(echo $phone |sed 's/\n//g') phone=$(echo $phone |sed 's/\r//g') sh /data/se_scripts/conf/send_msg_new.sh ${phone} 701 "upload $1 failed" &}function exit_if_timeout(){ SLEEP_SECONDS=$1 CMD=$2 #set -x $CMD & pidApp=$! ( sleep $SLEEP_SECONDS ; kill $pidApp ) & killerPid=$! wait $pidApp status=$? (kill -0 $killerPid && kill $killerPid) || true #set +x return $status}function exec_cmd_with_retry() { cmd=$1 cur_retry=$2 while [ $cur_retry -gt 0 ]; do $cmd ret=$? if [ $ret -eq 0 ]; then return fi ((cur_retry -= 1)) sleep 10 done send_sms "Failed to exec ${cmd} IP:${local_ip}" exit 1;}function upload_s3path(){ retry_cnt=$1 src_path=$2 file=$3 arr=(${file//./ }) day=${file:0:8} hour=${file:8:2} minute=${file:10:2} exit_if_timeout 600 "aws s3 cp --profile $s3_profile $src_path/$file $s3_path/$day/$hour/$minute/$file.$local_ip.log" ret=$? if [ $ret -eq 0 ] ; then rm -rf $src_path/$file fi if [ $ret -eq 0 ] && [ "${file}" != "${ln_file}" ]; then send_sms "$src_path/$file uploads3 retry ok ${local_ip}" elif [ $ret -ne 0 ] && [ $retry_cnt -eq 0 ]; then send_sms "$src_path/$file uploads3 failed ${local_ip}" fi}function upload_files(){ for f in `ls $ln_path` do upload_s3path $1 $ln_path $f done}function upload_empty(){ for f in `ls $lock_touch` do upload_s3path $1 $lock_touch $f done}function upload_logs(){ cur_retry=5 while [ $cur_retry -gt 0 ]; do upload_empty $cur_retry upload_files $cur_retry ((cur_retry -= 1)) sleep 10 done }#down 机 肯定不会有原始日志,所以不检查原始日志function check_empty(){ for f in `ls $lock_touch` do check=`ls $ln_path | grep $f | grep -v grep | wc -l` if [ $check -ne 0 ]; then rm -rf $lock_touch/$f fi done}function check_pid(){ if [ ! -d ${lock_pid} ];then mkdir -p $lock_pid echo $$ > $lock_pid/PID return fi check=0 running=`cat $lock_pid/PID` if [ ! -z $running ]; then check=`ps -ef | grep $running | grep -v grep | wc -l` fi if [ "$check" -eq "1" ]; then exit fi echo $$ > $lock_pid/PID}#argslog_path=$1log_file=$2s3_path=$3ln_path=$4ln_file=$6s3_profile=$7lock_pid=$5/pidlock_touch=$5/emptylocal_ip=`cat /var/tmp/ifconfigme`#soft linkexec_cmd_with_retry "ln -s $log_path/$log_file $ln_path/$ln_file" 5check_pidcheck_emptyupload_logsrm -rf $lock_pid 基本上已经够用了,需要定义自己的变量就好!