linux 日志条数动态实时统计

1、需求点
1)输入:日志实时更新:当前日志表以秒级更新日志,每秒有多条日志更新。格式如下:

2016-08-11 11:02:09
2016-08-11 11:02:09
2016-08-11 11:02:09
2016-08-11 11:02:09
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:11
2016-08-11 11:02:11
2016-08-11 11:02:11

2)实时输出:每个时刻值对应的2016-08-11 11:06:56 47
2016-08-11 11:06:57 18
2016-08-11 11:06:58 44
2016-08-11 11:06:59 22
2016-08-11 11:07:00 42
2016-08-11 11:07:01 44
2016-08-11 11:07:02 12
2016-08-11 11:07:03 37
2016-08-11 11:07:04 18
2016-08-11 11:07:05 18
2016-08-11 11:07:06 38
2016-08-11 11:07:07 48
2016-08-11 11:07:08 38
2016-08-11 11:07:09 21
2016-08-11 11:07:10 31
2016-08-11 11:07:11 18
2016-08-11 11:07:12 20
2016-08-11 11:07:13 3
2016-08-11 11:07:14 43
要求:一行脚本完成统计。

2、脚本实现原理
1)循环产生时间值,并写入文件。
时刻值的产生需要注意时间和时间戳的#时间形式打印
[root@laoyang zq_testing]# tcurtime=date "+%F %T"
[root@laoyang zq_testing]# echo $tcurtime
2016-08-11 11:15:06

2)时间转化为时间戳
[root@laoyang zq_testing]# scurtime=date -d "$tcurtime" +%s
[root@laoyang zq_testing]# echo $scurtime
1470885306

3)时间戳转化为时间
[root@laoyang zq_testing]# tcurtime=date -d @$scurtime "+%F %T"
[root@laoyang zq_testing]# echo $tcurtime
2016-08-11 11:15:06

4)循环环读取文件,使用awk的词频统计功能完成频率统计。
3、脚本实现
#构造时间脚本
[root@laoyang zq_testing]# cat build_time.sh
#!/bin/sh
#generate random values
function random()
{
  min=$1;
  max=$2
  randomval=$((RANDOM%$max+$min))
  echo $randomval
}

#generate time values
function build_conn_time()
{
  rm -rf ./output.log
  touch ./output.log
  cat /dev/null > ./output.log

  tflag=0
  nextsecond=0
  while :
  do
  if [[ $tflag -eq 0 ]];then
  tcurtime=`date "+%F %T"`
  echo "xtcurtime="$tcurtime
  tflag=1
  else
  #时间戳转化为时间
  tcurtime=`date -d @$nextsecond "+%F %T"`
  echo "next tcurtime="$tcurtime
  fi

  #时间格式化 为时间戳
  scurtime=`date -d "$tcurtime" +%s`

  #产生2-50之间的随机数
  cyccnt=$(random 2 50);
  if [[ -z $cyccnt ]]; then
  cyccnt=10
  fi
  echo "cyccnt="$cyccnt
  i=0
  while (( $i<$cyccnt))
  do
  echo $tcurtime >> output.log
  i=$(($i+1))
  done

  #更新下一秒 ,时间戳可以求和操作
  nextsecond=$(($scurtime+1))
  sleep 1
  done
}

build_conn_time;

一行指令完成统计
root@laoyang zq_testing]# while : ; do cat output.log | sort | awk '{ count[$0]++ }\
END { printf("%-14s %s\n","curtime","Count");\
for(ind in count)\
{ printf("%-14s %d\n",ind,count[ind]); } }' | sort ; sleep 1 ; done
 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值