ELKStack实战之Logstash [ 二 ]

Logstash介绍

Logstash是一个完全开源的工具,他可以对你的日志进行收集、分析,并将其存储供以后使用(如,搜索),您可以使用它。说到搜索,logstash带有一个web界面,搜索和展示所有日志.

首先LogStash是收集日志,它收集完日志就需要把日志存储下来,所以我们可以用运输者的身份来表示LogStash(INPUT or OUTPUT)``LogStash可以在日志发送之前做一个过滤OUTPUT之前.

LogStash三大功能

  • INPUT 进
  • FILTER (支持过滤的功能)
  • OUTPUT 出

LogStash部署与配置

Elasticsearch一样,在开始部署LogStash之前也需要你的环境中正确的安装的JDK。可以下载安装OracleJDK或者使用 yum安装openjdk

安装JDK

1
$ yum install -y java-1.8.0

YUM部署LogStash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 添加key
$ rpm --import https://packages.elastic.co/GPG-KEY-elasticsearch
// 配置yum
$ cat /etc/yum.repos.d/logstash.repo
[logstash-2.3]
name=Logstash repository for 2.3.x packages
baseurl=https://packages.elastic.co/logstash/2.3/centos
gpgcheck=1
gpgkey=https://packages.elastic.co/GPG-KEY-elasticsearch
enabled=1
// 安装logstash
$ yum -y install logstash

配置logstash

logstash实现inputouput主要是依赖于logstash有需多的插件

1
2
3
4
5
$ /opt/logstash/bin/logstash -e 'input { stdin{} } output { stdout{} }'
Settings: Default pipeline workers: 4
Pipeline main started
carey.akhack.com //输入(input)
2017-06-12T09:44:53.165Z localhost.localdomain carey.akhack.com //输出(output)

使用codec rubydebug功能,可读性增加

1
2
3
4
5
6
7
8
9
10
$ /opt/logstash/bin/logstash -e 'input { stdin{} } output { stdout{ codec => rubydebug } }'
Settings: Default pipeline workers: 4
Pipeline main started
carey.akhack.com //输入(input)
{
"message" => "carey.akhack.com",
"@version" => "1",
"@timestamp" => "2017-06-12T09:46:49.095Z",
"host" => "localhost.localdomain"
} //输出(output)

将日志写入es里面

官方文档地址:https://www.elastic.co/guide/en/logstash/current/first-event.html
INPUT插件:https://www.elastic.co/guide/en/logstash/current/input-plugins.html
OUTPUT插件:https://www.elastic.co/guide/en/logstash/current/output-plugins.html

配置主机及索引

1
2
3
4
$ /opt/logstash/bin/logstash -e 'input { stdin{} } output { elasticsearch { hosts => ["192.168.56.101:9200"] index => "logstash-%{+YYYY.MM.dd}%"} }'
Settings: Default pipeline workers: 4
Pipeline main started
carey.akhack.com //输入

这时已经写入到es中了,进入es中查看

点击数据浏览即可看到数据

编写配置文件

提示:

  • 配置文件的语法需要包含INPUT or OUTPUT,其中filter可以没有。
  • INPUTOUTPUT中的{}不可以搞错,其中INPUT存放INPUT插件,OUTPUT存放OUTPUT插件
    (其中插件也需要有{花括号}) =>代表等于,写一个数组需要使用[中括号]多个可以使用逗号分隔。
  • 字符串需要使用双引号
  • #号代表注释
  • 日志中信息都是一行一行的,在logstash中叫做事件(因为logstash可以将多行进行合并)
  • 流程: 事件 --> input --> codec --> filter --> codec --> output

收集mesassage错误日志

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$ cat /etc/logstash/conf.d/message.conf
input {
file {
path => ["/var/log/messages","/var/log/secure"]
type => "system-log"
start_position => "beginning"
}
}
filter {
}
output {
elasticsearch {
hosts => ["192.168.56.101:9200"]
index => "system-log-%{+YYYY.MM}"
}
}
// path 定义日志路径
// start_position 记录日志从头读取数据还是从尾读取数据
// type 可以设置类型,进行if判断(简单来说可以将日志进行分类,错误放在一起,正常放在一起)
// 提示:关于hosts后面端口可写可不写,不写默认是9200
1
$ /opt/logstash/bin/logstash -f /etc/logstash/conf.d/message.conf

进入web查看数据

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器