使用 ELK(elasticsearch/logstash/kibana)分析 nginx 日志

简介

作为一个后台开发,我们经常会用到日志,为了debug或验证一些问题,这时候只是需要在console找到某几行日志。
但是如果要有一个可视化的全局视图,还是需要借助一些工具,ELK就是常用的一套工具集。

版本兼容

以下版本亲测兼容:

  • Logstash 2.3.1

  • Elasticsearch 2.3.x

  • Kibana 4.5.0

Compatible with Elasticsearch 2.3.x. Kibana can also be installed from our repositories using apt or yum. See Repositories in the Guide.

Elasticsearch


主要作用:负责日志检索和分析。

tar xvf elasticsearch-2.3.2.tar.gz -C /foo/path
bin/elasticsearch

默认端口是:

Logstash


主要作用:负责日志的收集,处理和储存。

使用:

tar zxvf logstash-2.3.1.tar.gz
bin/logstash -e 'input { stdin { } } output { stdout {} }'
`-e`代表直接从命令行输入配置文件, input选择了标准输入, output选择了标准输出。

我们要做的是把nginx日志输出存储到Elasticsearch,使用 -f 指定配置:

bin/logstash -f logstash-nginx.conf

logstash-nginx.conf 是我们需要编写的配置文件,用以指定nginx日志的位置和格式,以及es的接口位置。

编写 logstash-nginx.conf

更多关于 logstash 配置文件 的编写, 请参考官方文档

假设nginx的日志格式为:

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

新建 logstash-nginx.conf 文件,写入:

#
input {
file {
path => [ "/home/niko/mount/hsb_D/niko/temp_trash/logs/foo.com.access_20160617.log" ]
type => "nginx-access"
start_position => "beginning"
}
}

#
filter {
grok {
match => {"message" => "%{IPORHOST:source_ip} - %{USERNAME:remote_user} \[%{HTTPDATE:timestamp}\] %{QS:request} %{INT:status} %{INT:body_bytes_sent} %{QS:http_referer} %{QS:http_user_agent}"}
}
}

#
output {
elasticsearch { hosts => ["localhost:9200"] }
}

启动后,等logstash处理完日志文件并写入es,可以查看es的索引:

http://localhost:9200/_cat/indices

可以看到以下内容:

yellow open .kibana             1 1 1 0  3.1kb  3.1kb
yellow open logstash-2016.04.28 5 1 4 0 12.3kb 12.3kb

grok 使用请看 grok 插件文档

以上grok解析nginx日志文件到es的配置,当然还可以从其他输入源(不止文件)获取数据,输出到不同位置(redis等其他中间件)。

kibana


主要作用:负责日志的可视化。

  • 使用:

    tar xf kibana-4.5.0-linux-x64.tar.gz -C /foo/path
    bin/kibana

  • visit localhost:5601

  • 配置index pattern:

  • 点击Settings, 在Indicestab, 创建一个index pattern,选择logstash-*

  • 点击visualization, Create a new visualization 这里选择Line Chart类型图

  • 然后选择X和Y坐标,Y有常见的聚合属性,X是nginx日志行的几个字段,完成后点击生成, 如下:

以上只是一个示例,kibana 的功能远强大于此,根据自己的需求去定制可视化吧。

参考


【1】https://github.com/elastic/examples/tree/master/ELK_NGINX
【2】http://www.icyfire.me/2014/11/13/logstash-es-kibana.html
【3】http://www.wklken.me/posts/2015/04/26/elk-for-nginx-log.html
【4】http://www.wklken.me/posts/2015/05/08/elk-data-collect.html