本文作者:罗海鹏,叩丁狼高级讲师。原创文章,转载请注明出处。
案例一:收集Nginx访问日志数据
Nginx是企业中常用的http服务器,也有人称它为反向代理服务器和负债均衡服务器,凭借着性能强大和功能完善在整个互联网行业中大量使用,所以收集Nginx服务器的访问日志数据,并且转存到elasticsearch中,就是一个很常见的需求了,然后再根据elasticsearch强大的搜索和聚合能力统计出我们的应用的访问量、访问用户所在地、访问了什么功能、访问时间和使用了什么客户端访问的等等信息。
首先,我们创建一个Logstash的配置文件,文件名随意,我们起名为:logstash.conf,在该文件中编辑input、filter和output这3个组件的配置。
然后,在启动Logstash实例的时候,使用-f
参数的方式启动,参数值为该配置文件的存放路径,比如:./logstash -f /soft/logstash_conf/logstash.conf
input {
file {
path => "/usr/local/nginx/logs/access.log"
type => "nginx-access"
start_position => "beginning"
}
}
我们使用了一个file的输入插件,读取的文件是nginx的访问日志access.log
,存放在:/usr/local/nginx/logs/
目录中。nginx访问日志默认格式为:
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
如果需要自定义访问日志的格式,只需要在nginx.conf配置文件中修改以上内容。
通过以上格式输出的日志会写到/usr/local/nginx/logs/access.log
文件中,内容为:192.168.85.1 - - [16/Sep/2018:00:42:38 +0800] "GET /catalog/getChildCatalog?catalogId=1 HTTP/1.1" 200 3249 "http://mgrsite.shop.com/" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
一旦nginx的访问日志有新的内容更新,会被Logstash监控到,并读取到Logstash中,然后Logstash为该数据流创建一个Event对象,我们可以在output组件中设置一个标准输出:stdout,在显示器打印Event对象,打印结果为:
{
"message" => "192.168.85.1 - - [16/Sep/2018:00:42:38 +0800] "GET /catalog/getChildCatalog?catalogId=1 HTTP/1.1" 200 3249 "http://mgrsite.shop.com/" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
"@version" => "1",
"@timestamp" => 2018-08-13T17:32:01.122Z,
"host" => "localhost.localdomain"
}
上面的打印结果就是一个Event对象,在该Event对象中的message字段封装了一条数据流的数据(注意:在上一节中,我们提到了file输入插件默认是以换行符作为一条数据流的,可以通过配置来设置数据流的分隔符)
filter {
grok {
match => {
"message" => "%{IP:remote_ip} \- \- \[%{HTTPDATE:timestamp}\] \"%{WORD:method} %{URIPATHPARAM:request} HTTP/%{NUMBER:http_version}\" %{NUMBER:status} %{NUMBER:bytes} \"%{URI:domain}\" \"%{GREEDYDATA:user_agent}"
}
remove_field => ["message","@timestamp","@version"]
}
date {
match => ["timestamp","dd/MMM/YYYY:HH:mm:ss Z"]
target => "timestamp"
}
if [remote_ip] !~ "^127\.|^192\.168\.|^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[01]\.|^10\." {
geoip {
source => "remote_ip"
}
}
}