从nginx日志中进行url解析

/v1/test?param2=v2&param3=v3&time=2019-03-18%2017%3A34%3A14
->
{'param1':'v1','param2':'v2','param3':'v3','time':'2019-03-18 17:34:14'}

nginx日志示例:

1.119.132.168 - - [18/Mar/2019:09:13:50 +0000] "POST /param1/test?param2=1&param3=2&time=2019-03-18%2017%3A34%3A14 HTTP/1.1" 200 929 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36" "-"

1 使用grok

input {

      file {

        path => [ "/var/log/nginx/access.log" ]
start_position => "beginning"
}
}
filter {
if [message] =~ /test/ {
grok {
match => { "message" => "%{IPORHOST:client_ip} (%{USER:ident}|-) (%{USER:auth}|-) \[%{HTTPDATE:access_time_raw}\] \"(?:%{WORD:verb} (/%{PARAMVALUE:param1}/test\?param2=%{PARAMVALUE:param2}&param3=%{PARAMVALUE:param3}&time=%{PARAMVALUE:send_time_raw})(?: HTTP/%{NUMBER:http_version})?|-)\" (%{NUMBER:response}|-) (?:%{NUMBER:bytes}|-) %{QS:referrer} %{QS:agent} %{QS:x_forward_for}" }
pattern_definitions => { "PARAMVALUE" => "[^& ]*" }
}
urldecode {
all_fields => true
}
date {
match => [ "access_time_raw","dd/MMM/yyyy:HH:mm:ss Z"]
target => "access_time_tmp"
}
ruby {
code => "event.set('access_time', (event.get('access_time_tmp').to_i * 1000000).to_s)
event.set('send_time', event.get('access_time'))"
}
if [send_time_raw] {
date {
match => [ "send_time_raw","yyyy-MM-dd HH:mm:ss"]
target => "send_time_tmp"
timezone => "UTC"
}
ruby {
code => "event.set('send_time', (event.get('send_time_tmp').to_i * 1000000).to_s)"
}
}
mutate {
remove_field => ["message", "ident", "auth", "verb", "bytes", "reponse", "x_forward_for", "http_version", "access_time_raw", "access_time_tmp", "path", "response", "send_time_raw", "send_time_tmp"]
}
} else {
drop {}
}
}
output {
if [param1] and [param2] and [param3] and "_grokparsefailure" not in [tags] {
stdout {codec => json}
}
}

注意:
1)对url的参数名和位置硬编码,不灵活
2)使用自定义pattern:PARAMVALUE
3)一定要使用urldecode,否则time得到的value为2019-03-18%2017%3A34%3A14,logstash中date插件使用joda解析pattern会报错,因为含有字母A;
4)如果time为空,则使用access_time;
5)不匹配的记录drop掉;
6)只有满足条件的记录才会被output;
7)在filter和output中使用if-else定义分支;
8)date插件要注意timezone,否则会按照时区偏移;

2 使用grok+ruby


input {
    file {
      path => [ "/var/log/nginx/access.log" ]
      start_position => "beginning"
    }
  }


filter {
if [message] =~ /test/ {
grok {
match => { "message" => "%{IPORHOST:client_ip} (%{USER:ident}|-) (%{USER:auth}|-) \[%{HTTPDATE:access_time_raw}\] \"(?:%{WORD:verb} (%{URIPATHPARAM:request}|-)(?: HTTP/%{NUMBER:http_version})?|-)\" (%{NUMBER:response}|-) (?:%{NUMBER:bytes}|-) %{QS:referrer} %{QS:agent}" }
}
urldecode {
all_fields => true
}
date {
match => [ "access_time_raw","dd/MMM/yyyy:HH:mm:ss Z"]
target => "access_time_tmp"
}
ruby {
code => "event.set('access_time', (event.get('access_time_tmp').to_i * 1000000).to_s)
event.set('send_time', event.get('access_time'))"
}
if [request] {
ruby {
          init => "
          def convertName(name)
              result = ''
              name.each_char{|ch| result += (if ch < 'a' then '_' + ch.downcase else ch end)}
              result
          end
          "
code => "
event.set('param1', event.get('request').split('?')[0].split('/')[1])
pairs = event.get('request').split('?')[1].split('&')
pairs.each{ |item| arr=item.split('='); event.set(arr[0], arr[1])}
"
}
if [time] {
date {
match => [ "time","yyyy-MM-dd HH:mm:ss"]
target => "send_time_tmp"
timezone => "UTC"
}
ruby {
code => "event.set('send_time', (event.get('send_time_tmp').to_i * 1000000).to_s)"
}
}
}
mutate {
remove_field => ["message", "ident", "auth", "verb", "bytes", "reponse", "x_forward_for", "http_version", "access_time_raw", "access_time_tmp", "path", "response", "time", "send_time_tmp"]
}
} else {
drop {}
}
}
output {
if [param1] and [param2] and [param3] and "_grokparsefailure" not in [tags] {
stdout {codec => json}
}
}

注意:
1)直接使用默认的nginx日志的grok pattern;
2)在ruby中直接按照key=value进行解析,更灵活;
3)自定义函数;

logstash的ruby代码中getter和setter必须使用代码,比如event.get('field'),不能使用event['field'],因为

[2019-03-19T17:15:32,729][ERROR][logstash.filters.ruby ] Ruby exception occurred: Direct event field references (i.e. event['field'] = 'value') have been disabled in favor of using event get and set methods (e.g. event.set('field', 'value')). Please consult the Logstash 5.0 breaking changes documentation for more details.

3 使用grek+kv

input {
file {
path => [ "/data/tmp/access.log" ]
start_position => "beginning"
}
} filter {
if [message] =~ /dataone\/u1/ {
grok {
match => { "message" => "%{IPORHOST:client_ip} (%{USER:ident}|-) (%{USER:auth}|-) \[%{HTTPDATE:access_time_raw}\] \"(?:%{WORD:verb} (%{URIPATHPARAM:request}|-)(?: HTTP/%{NUMBER:http_version})?|-)\" (%{NUMBER:response}|-) (?:%{NUMBER:bytes}|-) %{QS:referrer} %{QS:agent}" }
}
kv {
source => "request"
field_split => "&?"
value_split => "="
}
urldecode {
all_fields => true
}
date {
match => [ "access_time_raw","dd/MMM/yyyy:HH:mm:ss Z"]
target => "access_time_tmp"
}
ruby {
code => "event.set('access_time', (event.get('access_time_tmp').to_i * 1000000).to_s)
event.set('send_time', event.get('access_time'))"
}
if [send_time_raw] {
date {
match => [ "send_time_raw","yyyy-MM-dd HH:mm:ss"]
target => "send_time_tmp"
}
ruby {
code => "event.set('send_time', (event.get('send_time_tmp').to_i * 1000000).to_s)"
}
}
mutate {
remove_field => ["message", "ident", "auth", "verb", "bytes", "reponse", "x_forward_for", "http_version", "access_time_raw", "access_time_tmp", "path", "response", "send_time_raw", "send_time_tmp"]
}
} else {
drop {}
}
}

参考:https://www.elastic.co/guide/en/logstash/current/plugins-filters-kv.html

【原创】大数据基础之Logstash(3)应用之file解析(grok/ruby/kv)的更多相关文章

  1. 【原创】大数据基础之Zookeeper(2)源代码解析

    核心枚举 public enum ServerState { LOOKING, FOLLOWING, LEADING, OBSERVING; } zookeeper服务器状态:刚启动LOOKING,f ...

  2. 【原创】大数据基础之Logstash(1)简介、安装、使用

    Logstash 6.6.2 官方:https://www.elastic.co/products/logstash 一 简介 Centralize, Transform & Stash Yo ...

  3. 【原创】大数据基础之Logstash(4)高可用

    logstash高可用体现为不丢数据(前提为服务器短时间内不可用后可恢复比如重启服务器或重启进程),具体有两个方面: 进程重启(服务器重启) 事件消息处理失败 在logstash中对应的解决方案为: ...

  4. 【原创】大数据基础之Logstash(3)应用之http(in和out)

    一个logstash很容易通过http打断成两个logstash实现跨服务器或者跨平台间数据同步,比如原来的流程是 logstash: nginx log -> kafka 打断成两个是 log ...

  5. 【原创】大数据基础之Logstash(2)应用之mysql-kafka

    应用一:mysql数据增量同步到kafka 1 准备mysql测试表 mysql> create table test_sync(id int not null auto_increment, ...

  6. 【原创】大数据基础之Logstash(5)监控

    有两种方式来监控logstash: api ui(xpack) When you run Logstash, it automatically captures runtime metrics tha ...

  7. 【原创】大数据基础之Logstash(6)mongo input

    logstash input插件之mongodb是第三方的,配置如下: input { mongodb { uri => 'mongodb://mongo_server:27017/db' pl ...

  8. 【原创】大数据基础之词频统计Word Count

    对文件进行词频统计,是一个大数据领域的hello word级别的应用,来看下实现有多简单: 1 Linux单机处理 egrep -o "\b[[:alpha:]]+\b" test ...

  9. 【原创】大数据基础之Impala(1)简介、安装、使用

    impala2.12 官方:http://impala.apache.org/ 一 简介 Apache Impala is the open source, native analytic datab ...

随机推荐

  1. jspdf简单使用

    安装 npm install jspdf --save 英文输出 import jsPDF from 'jspdf-customfonts' let doc = new jsPDF() doc.tex ...

  2. Spring Bean的ref属性和IoC注入集合

    这是一个Demo 1.Phone.java package com.cn.pojo; public class Phone { private String name; private double ...

  3. C++ 出现异常“.... \debug_heap.cpp Line:980 Expression:__acrt_first_block==header"

    本人是在写dll项目中出现了这个问题,经过一天的研究,尝试了三个步骤1.在配置属性->常规->MFC的使用中,将在静态库中使用MFC改为在共享DLL中使用MFC.但是还会出错2.原因是dl ...

  4. Python3快速入门

    ——<趣学Python-教孩子学编程>学习笔记 1.注释 (1)单行注释以  #  开头注释 # 这是一个注释 print("Hello, World!") (2)多行 ...

  5. Linux C 编程

    主题链接地址:https://www.cnblogs.com/kele-dad/category/1194627.html

  6. Linux之vi编辑器的使用

    今天我们来说一下vi编辑器的使用,vi编辑器主要用来在Linux环境下编辑配置文件. 一.使用方法: 1.输入命令 vi filename,打开文件,处于一个查看模式 2.点击键盘 i,进入inser ...

  7. 🍓 react16.2新特性 🍓

    react16.2新特性:组件中可以一次性return 多个子元素(子组件)了,也就是说,想return多个子元素,不用在外面包一个父盒子了. 方法一:把要return的元素放在一个空的jsx里面 方 ...

  8. mysql案例~非常规操作汇总

    一 简介:此文汇总mysql不常见的数据库的操作二 mysql表修改最大自增ID 目的: 修复canal相关问题 语法: alter table a AUTO_INCREMENT=num; 执行速度: ...

  9. 设置eclipse代码自动补全功能

    1.选择Eclipse菜单条中的Windows菜单下的Preferences项 2.在左侧找到“Java” -> “Editor” -> “Content Assist” 3.在右侧“Au ...

  10. Django实战(一)-----用户登录与注册系统3(前端页面、登录视图)

    基本框架搭建好了后,我们就要开始丰富页面内容了.最起码,得有一个用户登录的表单不是么?(注册的事情我们先放一边.) 一. 原生HTML页面 删除原来的login.html文件中的内容,写入下面的代码: ...