【问题标题】:Using awk to generate report from apache http logs使用 awk 从 apache http 日志生成报告
【发布时间】:2017-07-02 10:11:54
【问题描述】:

希望有人可以帮助我使用 bash linux 脚本从 http 日志生成报告。

日志格式:

domain.com 101.100.144.34 - r.c.bob [14/Feb/2017:11:31:20 +1100] "POST /webmail/json HTTP/1.1" 200 1883 "https://example.domain.com/webmail/index-rui.jsp?v=1479958955287" "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko" 1588 2566 "110.100.34.39" 9FC1CC8A6735D43EF75892667C08F9CE 84670 - - - -  

输出要求:

time in epoch,host,Resp Code,count  

1485129842,101.100.144.34,200,4000  
1485129842,101.101.144.34,404,1889

到目前为止我所拥有的,但与我想要实现的目标相去甚远:

tail -100 httpd_access_*.log | awk '{print  $5 " " $2 " " $10}' | sort | uniq

【问题讨论】:

  • 日志内容是否持续增长?在这种情况下,您可能需要禁用缓冲。

标签: linux bash apache awk


【解决方案1】:
awk 'BEGIN{
   # print header
   print "time in epoch,host,Resp Code,count"
   # prepare month conversion array
   split( "Jan Feb Mar Apr May Jun Jui Aug Sep Oct Nov Dec", tmp)
   for (i in tmp) M[tmp[i]]=i
   }

   {
   #prepare time conversion for mktime() using array and substitution
   # from 14/Feb/2017:11:31:20 +1100
   # to YYYY MM DD HH MM SS [DST]
   split( $5, aT, /[:/[:blank:]]/)
   t = $5; sub( /^.*:|:/, " ", t)
   t = aT[3] " " M[aT[2]] " " aT[1] t

   # count (not clear if it s this to count due to time changing
   Count[ sprintf( "%s, %s, %s", mktime( t), $2, $10)]++
   }

   END{
      # disply the result counted
      for( e in Count) printf( "%s, %d\n", e, Count[e])
      }
   ' httpd_access_*.log
  • 计数将更具体地描述以确保计数标准
  • mktime() 函数需要 GNU awk
  • 假设时间始终采用这种格式
  • 没有安全也没有过滤器(不是这个目的)

【讨论】:

    【解决方案2】:

    当然,上面的纯 AWK 解决方案会更快、更完整。 但也可以分小步完成:

    首先获取日期并将其转换为 EPOCH:

    $ dt=$(awk '{print $5,$6}' file.log)
    $ ep=$(date -d "$(sed -e 's,/,-,g' -e 's,:, ,' <<<"${dt:1:-1}")" +"%s")
    $ echo "$ep"
    1487032280
    

    由于现在您在 bash var $ep 中有纪元日期,因此您可以像这样继续使用您的初始 awk:

    $ awk -v edt=$ep '{print edt","$2","$10}' file.log
    1487032280,101.100.144.34,200
    

    如果你想要一个标题,你可以在最后一个 awk 之前用一个简单的 echo 打印一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-21
      • 1970-01-01
      • 2015-11-02
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多