日期:2014-05-16  浏览次数:20753 次

linux shell日志工具类 可以记录日志用

#!/bin/sh

logpath="/home/log/"
currenttime=`date "+%Y%m%d"`
fileSize=1024
loglevel=$1
logmessage=$2
logfilename=""

createfile()
{
    getLastLogFileName $logpath
    filename=$logfilename
    isNeedNewFile $filename
    result=$?
    if [ $result -eq 0 ];then
        logfilename=${logpath}${currenttime}`date "+%H%M%S"`.log
    elif [ $result -eq 2 ];then
        logfilename=${logpath}${currenttime}`date "+%H%M%S"`.log
    else
        logfilename=${logpath}$filename
    fi
}

isNeedNewFile()
{
    filename=$1

    if [ -z $filename ]; then
        return 2
    fi
   
    if [ -f $filename ];then
        size=`ls -l $filename | awk '{print $5}'`
        if [ $size -gt $fileSize ];then
           return 0
        else
            return 1
        fi
    else
        return 2
    fi
}

write_log ()
{
              createfile
              level=$1
              msg=$2
              case $level in
               debug)
               echo "[DEBUG] `date "+%Y%m%d%H%M%S"` : $msg  " >> $logfilename
               ;;
               info)
               echo "[INFO] `date "+%Y%m%d%H%M%S"` : $msg  " >> $logfilename
               ;;
               error)
               echo "[ERROE] `date "+%Y%m%d%H%M%S"` : $msg  " >> $logfilename
               ;;
               *)
               echo "error......" >> $logfilename
               ;;
               esac
}

getLastLogFileName()
{
    path=$1
    cd $path
    lastLog=`ls -l |grep $currenttime | sort -k8rn | head -1 |awk '{print $9}'`

    logfilename=$lastLog
}

 

#write_log $loglevel $logmessage