scala解析一段日志

日志文件,格式如下: # Http-Method IP/domain timesGET www.baidu.com 1234GET www.qq.com 123GET 127.0.0.1 123 GET 10.123.76.3 12 GET 10.123.76.4 343 统计对所有IP的GET请求数, 比如上述的例子已经返回478

import java.io._
import scala.io._

def parseLog(is: InputStream): Iterator[String] = {   
   Source.fromInputStream(is).getLines()
}

def countGET(iter: Iterator[String]): Int ={
   iter.filter{
     line => 
     val l = line.trim; 
     l.length > 0 && !l.startsWith("#")
   }.filter{
     line =>        
        val strs = line.trim.split("\\s+");
    //  println(strs.toList+"  "+strs.length);
        strs(0).equalsIgnoreCase("GET") &&  strs(1).matches("""\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}""");
   }.map{
      line => line.trim.split("\\s+")(2);
   }.foldLeft(0){
     (x, y) => x.toInt + y.toInt
   }
}

println(countGET(parseLog(new FileInputStream(args(0)))));
原文:http://outofmemory.cn/code-snippet/37055/parse-yiduan-rizhi


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值