Scala解析Nginx日志为对象

/**
  * Nginx日志数据转换类
  */
object NginxLogParser{
  /**
    * 解析正则表达式
    * .r用于指明PARTTERN是一个正则表达式对象
    * 9个值:客户端访问IP、用户标识clientIdentd、用户userId、访问时间dateTime、请求方式mode、请求状态responseCode、返回文件的大小contentSize、跳转来源referrer、UA信息
    */
  val PATTERN =
    """(\S+) (\S+) (\S+) (\[.*\]) (\".*\") (\d{3}) (\d+) (\".*?\") (\".*?\")""".r

  def parseLog2Line(log: String): AccessLog = {
      def makeWifiLogs(): AccessLog = {
        new AccessLog("", "", "", "", "", 0, 0, "", "")
      }

      if (log.isEmpty) {
        val logs = PATTERN.findFirstMatchIn(log)
        if (logs.isEmpty) {
          throw new RuntimeException("Cannot parse log line: " + log)
        }
        val m = logs.get
        new AccessLog(m.group(1), m.group(2), m.group(3), m.group(4),m.group(5), m.group(6).toInt,
        m.group(7).toLong, m.group(8), m.group(9))
      }else{
      makeWifiLogs()
    }
  }

  def main(args: Array[String]) {
    val line = """111.128.69.30 - - [11/Sep/2018:00:01:00 +0800] "GET /api/getinfo.php?tid=1e35c7b357cd&rid=059e15c97800&gw=gaoke.com&did=2424826&sn=GAOKE_Q330&action=run HTTP/1.1" 200 315 "http://gaoke.com:8848/wx.html?tid=1e35c7b357cd&rid=059e15c97800&gw=gaoke.com&did=2424826&sn=GAOKE_Q330" "Mozilla/5.0 (Linux; Android 6.0; S9 Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36" "-""""

    val log = NginxLogParser.parseLog2Line(line);
    println(log.ip)
    println(log.clientIdent)
    println(log.userId)
    println(log.timestamp)
    println(log.request)
    println(log.responseCode)
    println(log.contentSize)
    println(log.referrer)
  }
}
/**
  * 日志文件对象
  */
case class AccessLog(
  ip: String,            //设备用户的真实ip地址
  clientIdent: String,   //用户标识
  userId: String,        //用户
  timestamp: String,     //访问日期时间
  request: String,       //请求信息,get/post,mac值等
  responseCode: Int,     //请求状态 200成功,304静态加载
  contentSize: Long,     //返回文件的大小
  referrer: String,      //跳转来源
  ua: String             //UA信息
//  forward:String //跳转页面

) extends Serializable {
  override def toString: String = ip+","+clientIdent+","+userId+","+timestamp+","+request+","+responseCode+","+contentSize+","+referrer+","+ua
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

訾零

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值