SHELL随笔 日志条目时间比较

  • 背景

    提供DLL函数给客户调用。为了方便调试,每个函数被调用时都会写一条日志。状态函数调用间隔为2s。

    日志格式

    2014:03:04 06:04:06 [Interface.cpp:Function1:100] doing ......

    2014:03:04 06:04:07 [Interface.cpp:Function2:100] doing ......

  • 需求

    检查函数调用间隔时间是否大于2s。

  • 实现

    使用以下shell脚本    

#! /bin/sh                            
                                      
LOG_FILE=/tmp/dll.txt                 
tv1=0                                 
tv2=0                                 
cat $LOG_FILE | while read line       
do                                    
    time_str=`echo $line | cut -c -19`
                                      
    if [ $tv1 -eq 0 ]; then           
        tv1=`date -d "$time_str" +%s`
    fi                               
                                           
    if [ $tv2 -eq 0 ]; then                
        tv2=`date -d "$time_str" +%s`      
    fi               
  
    inter=`expr $tv2 - $tv1`               
    if [ $inter -gt 2 ]; then              
        echo tv1:$tv1 tv2:$tv2 inter:$inter
        echo $tv1 $line                    
    fi                                     
    tv1=$tv2                               
    tv2=0                                  
                                           
done     
  • 备注
    • cut

    echo $line | cut -c -19 

    取一行的前19个字符

    即 echo "2014:03:04 06:04:06 [Interface.cpp:Function1:100] doing" | cut -c -19

    结果为 2014:03:04 06:04:06

    • date

date -d "$time_str" +%s

即 date -d “2014:03:04 06:24:03” +%s,

结果为:1401112983

    

 

    

posted on 2014-03-04 17:50  黄色的泥塘  阅读(589)  评论(0)    收藏  举报

导航