ELK 日志收集系统快速搭建

ELK 是一个分布式、可扩展、实时的搜索与数据分析引擎。目前我在工作中只用来收集 server 的 log, 开发锅锅们 debug 的好助手。

单节点 ELK

如果你想快速的搭建单节点 ELK, 那么使用 docker 方式肯定是你的最佳选择。使用三合一的镜像,文档详情
注意:安装完 docker, 记得设置 mmap counts 大小至少 262144
什么是 mmap

1
2
3
4
5
6
7
8
9
10
11
# 设置 mmap 命令
sysctl -w vm.max_map_count=262144

# 安装 docker
sudo yum install -y yum-utils device-mapper-persistent-data lvm2

sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

sudo yum install -y docker-ce

sudo systemctl start docker

单节点的机器,不必暴露 9200(Elasticsearch JSON interface) 和 9300(Elasticsearch transport interface) 端口。
如果想在 docker 上暴露端口,用 -p 如果没有填写监听的地址,默认是 0.0.0.0 所有的网卡。建议还是写明确监听的地址,安全性更好。

1
2
-p 监听的IP:宿主机端口:容器内的端口
-p 192.168.10.10:9300:9300

命令行启动一个 ELK

1
2
3
4
5
sudo docker run -p 5601:5601 -p 5044:5044 \
-v /data/elk-data:/var/lib/elasticsearch \
-v /data/elk/logstash:/etc/logstash/conf.d \
-it -e TZ="Asia/Singapore" -e ES_HEAP_SIZE="20g" \
-e LS_HEAP_SIZE="10g" --name elk-ubuntu sebp/elk

将配置和数据挂载出来,即使 docker container 出现了问题。可以立即销毁再重启一个,服务受影响的时间很短。

1
2
3
4
5
# 注意挂载出来的文件夹的权限问题
chmod 755 /data/elk-data
chmod 755 /data/elk/logstash
-v /data/elk-data:/var/lib/elasticsearch # 将 elasticsearch 存储的数据挂载出来,数据持久化。
-v /data/elk/logstash:/etc/logstash/conf.d # 将 logstash 的配置文件挂载出来,方便在宿主机上修改。

只需要配置logstash

接下来,我们再来看一看 logstash.conf 记得看注释
参考链接:

  1. SSL详情可参考
  2. grok 正则捕获
  3. grok插件语法介绍
  4. logstash 配置语法
  5. grok 内置 pattern
  6. Logstash详细记录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
input {
beats {
port => 5044
#ssl => true
#ssl_certificate => "/etc/logstash/logstash.crt"
#ssl_key => "/etc/logstash/logstash.key"
# 1. SSL详情可参考
}
}
# filter 模块主要是数据预处理,提取一些信息,方便 elasticsearch 好归类存储。
# 2. grok 正则捕获
# 3. grok插件语法介绍
# 4. logstash 配置语法
# 5. grok 内置 pattern
filter {
grok {
match => {"message" => "%{EXIM_DATE:timestamp}\|%{LOGLEVEL:log_level}\|%{INT:pid}\|%{GREEDYDATA}"}
# message 字段是 log 的内容,例如 2018-12-11 23:46:47.051|DEBUG|3491|helper.py:85|helper._save_to_cache|shop_session
# 在这里我们提取出了 timestamp log_level pid,grok 有内置定义好的patterns: EXIM_DATE, EXIM_DATE, INT
# GREEDYDATA 贪婪数据,代表任意字符都可以匹配
}
# 我们在 filebeat 里面添加了这个字段[fields][function]的话,那就会执行对应的 match 规则去匹配 path
# source 字段就是 log 的来源路径,例如 /var/log/nginx/feiyang233.club.access.log
# match 后我们就可以得到 path=feiyang233.club.access
if [fields][function]=="nginx" {
grok {
match => {"source" => "/var/log/nginx/%{GREEDYDATA:path}.log%{GREEDYDATA}"}
}
}
# 例如 ims 日志来源是 /var/log/ims_logic/debug.log
# match 后我们就可以得到 path=ims_logic
else if [fields][function]=="ims" {
grok {
match => {"source" => "/var/log/%{GREEDYDATA:path}/%{GREEDYDATA}"}
}
}

else {
grok {
match => {"source" => "/var/log/app/%{GREEDYDATA:path}/%{GREEDYDATA}"}
}
}
# filebeat 有定义 [fields][function] 时,我们就添加上这个字段,例如 QA
if [fields][function] {
mutate {
add_field => {
"function" => "%{[fields][function]}"
}
}
}
# 因为线上的机器更多,线上的我默认不在 filebeat 添加 function,所以 else 我就添加上 live
else {
mutate {
add_field => {
"function" => "live"
}
}
}
# 在之前 filter message 时,我们得到了 timestamp,这里我们修改一下格式,添加上时区。
date {
match => ["timestamp" , "yyyy-MM-dd HH:mm:ss Z"]
target => "@timestamp"
timezone => "Asia/Singapore"
}
# 将之前获得的 path 替换其中的 / 替换为 - , 因为 elasticsearch index name 有要求
# 例如 feiyang/test feiyang_test
mutate {
gsub => ["path","/","-"]
add_field => {"host_ip" => "%{[fields][host]}"}
remove_field => ["tags","@version","offset","beat","fields","exim_year","exim_month","exim_day","exim_time","timestamp"]
}
# remove_field 去掉一些多余的字段
}
# 单节点 output 就在本机,也不需要 SSL, 但 index 的命名规则还是需要非常的注意
output {
elasticsearch {
hosts => ["localhost:9200"]
index => "sg-%{function}-%{path}-%{+xxxx.ww}"
# sg-nginx-feiyang233.club.access-2019.13 ww代表周数
}
}

最终的流程图如下所示
log
index 的规则 参考链接

  • Lowercase only
  • Cannot include \, /, *, ?, “, <, >, |, ` ` (space character), ,, #
  • Indices prior to 7.0 could contain a colon (:), but that’s been deprecated and won’t be supported in 7.0+
  • Cannot start with -, _, +
  • Cannot be . or ..
  • Cannot be longer than 255 bytes (note it is bytes, so multi-byte characters will count towards the 255 limit faster)

filebeat 配置

在 client 端,我们需要安装并且配置 filebeat 请参考
Filebeat 模块与配置
配置文件 filebeat.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
filebeat.prospectors:
- input_type: log
paths: # 需要收集的日志
- /var/log/app/**/debug.log*

fields: #需要添加的字段
host: "{{inventory_hostname}}"
function: "xxx"
multiline: # 多行匹配
match: after
negate: true # pay attention the format
pattern: '^\[[0-9]{4}-[0-9]{2}-[0-9]{2}'
ignore_older: 24h
clean_inactive: 72h

output.logstash:
hosts: ["{{elk_server}}:25044"]
# ssl:
# certificate_authorities: ["/etc/filebeat/logstash.crt"]

批量部署 filebeat.yml 最好使用 ansible

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
---
- hosts: all
become: yes
gather_facts: yes
tasks:
- name: stop filebeat
service:
name: filebeat
state: stopped
enabled: yes

- name: upload filebeat.yml
template:
src: filebeat.yml
dest: /etc/filebeat/filebeat.yml
owner: root
group: root
mode: 0644

- name: remove
file: #delete all files in this directory
path: /var/lib/filebeat/registry
state: absent

- name: restart filebeat
service:
name: filebeat
state: restarted
enabled: yes

Kibana 简单的使用

在搭建 ELK 时,暴露出来的 5601 端口就是 Kibana 的服务。
访问 http://your_elk_ip:5601
kibana

集群 ELK 版本 6.7

集群主要是高可用,多节点的 Elasticsearch 还可以扩容。本文中用的官方镜像 The base image is centos:7

Elasticsearch 多节点搭建

官方安装文档 Elasticsearch

1
2
3
4
5
6
# 挂载出来的文件夹权限非常的重要
mkdir -p /data/elk-data && chmod 755 /data/elk-data
docker run -p WAN_IP:9200:9200 -p 10.66.236.116:9300:9300 \
-v /data/elk-data:/usr/share/elasticsearch/data \
--name feiy_elk \
docker.elastic.co/elasticsearch/elasticsearch:6.7.0

接下来是修改配置文件 elasticsearch.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Master 节点 node-1
# 进入容器 docker exec -it [container_id] bash
# docker exec -it 70ada825aae1 bash
# vi /usr/share/elasticsearch/config/elasticsearch.yml
cluster.name: "feiy_elk"
network.host: 0.0.0.0
node.master: true
node.data: true
node.name: node-1
network.publish_host: 10.66.236.116
discovery.zen.ping.unicast.hosts: ["10.66.236.116:9300","10.66.236.118:9300","10.66.236.115:9300"]

# exit
# docker restart 70ada825aae1

1
2
3
4
5
6
7
8
9
10
11
12
# slave 节点 node-2
# 进入容器 docker exec -it [container_id] bash
# vi /usr/share/elasticsearch/config/elasticsearch.yml
cluster.name: "feiy_elk"
network.host: "0.0.0.0"
node.name: node-2
node.data: true
network.publish_host: 10.66.236.118
discovery.zen.ping.unicast.hosts: ["10.66.236.116:9300","10.66.236.118:9300","10.66.236.115:9300"]

# exit
# docker restart 70ada825aae1
1
2
3
4
5
6
7
8
9
10
11
12
# slave 节点 node-3
# 进入容器 docker exec -it [container_id] bash
# vi /usr/share/elasticsearch/config/elasticsearch.yml
cluster.name: "feiy_elk"
network.host: "0.0.0.0"
node.name: node-3
node.data: true
network.publish_host: 10.66.236.115
discovery.zen.ping.unicast.hosts: ["10.66.236.116:9300","10.66.236.118:9300","10.66.236.115:9300"]

# exit
# docker restart 70ada825aae1

检查集群节点个数,状态等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# curl http://wan_ip:9200/_cluster/health?pretty
{
"cluster_name" : "feiy_elk",
"status" : "green",
"timed_out" : false,
"number_of_nodes" : 3,
"number_of_data_nodes" : 3,
"active_primary_shards" : 9,
"active_shards" : 18,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0,
"delayed_unassigned_shards" : 0,
"number_of_pending_tasks" : 0,
"number_of_in_flight_fetch" : 0,
"task_max_waiting_in_queue_millis" : 0,
"active_shards_percent_as_number" : 100.0
}

最终结果图在 kibana 上可以看到集群状态
elk

Kibana 搭建

官方安装文档 Kibana

1
2
3
4
5
6
# docker run --link YOUR_ELASTICSEARCH_CONTAINER_NAME_OR_ID:elasticsearch -p 5601:5601 {docker-repo}:{version}
docker run -p 外网IP:5601:5601 --link elasticsearch容器的ID:elasticsearch docker.elastic.co/kibana/kibana:6.7.0

# 注意的是 --link 官方其实并不推荐的,推荐的是 use user-defined networks https://docs.docker.com/network/links/
# 测试不用 --link 也可以通。直接用容器的 IP
docker run -p 外网IP:5601:5601 docker.elastic.co/kibana/kibana:6.7.0

we recommend that you use user-defined networks to facilitate communication between two containers instead of using –link

1
2
3
4
5
6
7
8
9
10
# vi /usr/share/kibana/config/kibana.yml
# 需要把 hosts IP 改为 elasticsearch 容器的 IP
# 如何查看 docker inspect elasticsearch_ID
server.name: kibana
server.host: "0.0.0.0"
elasticsearch.hosts: [ "http://172.17.0.2:9200" ]
xpack.monitoring.ui.container.elasticsearch.enabled: true

# 退出容器并重启
docker restart [container_ID]

Logstash 搭建

官方安装文档 Logstash

1
2
3
4
# docker -d 以后台的方式启动容器  --name 参数显式地为容器命名
docker run -p 5044:5044 -d --name test_logstash docker.elastic.co/logstash/logstash:6.7.0
# 也可以指定网卡,监听在内网或者外网 监听在内网 192.168.1.2
docker run -p 192.168.1.2:5044:5044 -d --name test_logstash docker.elastic.co/logstash/logstash:6.7.0

1
2
3
4
# vi /usr/share/logstash/pipeline/logstash.conf
# 配置详情请参考下面的链接,记得 output hosts IP 指向 Elasticsearch 的 IP
# Elasticsearch 的默认端口是9200,在下面的配置中可以省略。
hosts => ["IP Address 1:port1", "IP Address 2:port2", "IP Address 3"]

logstash 过滤规则 见上文的配置和 grok 语法规则

1
2
3
4
5
6
# vi /usr/share/logstash/config/logstash.yml
# 需要把 url 改为 elasticsearch master 节点的 IP
http.host: "0.0.0.0"
xpack.monitoring.elasticsearch.url: http://elasticsearch_master_IP:9200
node.name: "feiy"
pipeline.workers: 24 # same with cores

改完配置 exit 从容器里退出到宿主机,然后重启这个容器。更多配置详情,参见官方文档

1
2
3
4
# 如何查看 container_ID
docker ps -a

docker restart [container_ID]

容灾测试

我们把当前的 master 节点 node-1 关机,通过 kibana 看看集群的状态是怎样变化的。
elk1
当前集群的状态变成了黄色,因为还有 3 个 Unassigned Shards。颜色含义请参考官方文档,再过一会发现集群状态变成了绿色。
elk2

Welcome to Console

Quick intro to the UI
The Console UI is split into two panes: an editor pane (left) and a response pane (right). Use the editor to type requests and submit them to Elasticsearch. The results will be displayed in the response pane on the right side.

Console understands requests in a compact format, similar to cURL:

1
2
3
4
5
6
7
8
# index a doc
PUT index/type/1
{
"body": "here"
}

# and get it ...
GET index/type/1

While typing a request, Console will make suggestions which you can then accept by hitting Enter/Tab. These suggestions are made based on the request structure as well as your indices and types.

A few quick tips, while I have your attention

  • Submit requests to ES using the green triangle button.
  • Use the wrench menu for other useful things.
  • You can paste requests in cURL format and they will be translated to the Console syntax.
  • You can resize the editor and output panes by dragging the separator between them.
  • Study the keyboard shortcuts under the Help button. Good stuff in there!

Console 常用的命令

Kibana 控制台
ELK技术栈中的那些查询语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
GET _search
{
"query": {
"match_all": {}
}
}

GET /_cat/health?v

GET /_cat/nodes?v

GET /_cluster/allocation/explain

GET /_cluster/state

GET /_cat/thread_pool?v

GET /_cat/indices?health=red&v

GET /_cat/indices?v

PUT /*/_settings
{
"index" : {
"number_of_replicas" : 0,
"refresh_interval": "30s"
}
}

GET /_template

PUT _template/app-logstash
{
"index_patterns": ["logstash-*app-*"],
"settings": {
"number_of_shards": 3,
"number_of_replicas": 0,
"refresh_interval": "30s"
}
}

踩过的坑

  • iptables 防不住。需要看上一篇博客里的 iptable 问题。
  • elk 网络问题
  • elk node
  • discovery.type=single-node 在测试单点时可用,搭建集群时不能设置这个环境变量,详情见官方文档
  • ELK的一次吞吐量优化
  • filebeat 版本过低导致 recursive glob patterns ** 不可用
    用 ansible 升级 filebeat
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    ---
    - hosts: all
    become: yes
    gather_facts: yes
    tasks:
    - name: upload filebeat.repo
    copy:
    src: elasticsearch.repo
    dest: /etc/yum.repos.d/elasticsearch.repo
    owner: root
    group: root
    mode: 0644

    - name: install the latest version of filebeat
    yum:
    name: filebeat
    state: latest

    - name: restart filebeat
    service:
    name: filebeat
    state: restarted
    enabled: yes

    # elasticsearch.repo
    [elasticsearch-6.x]
    name=Elasticsearch repository for 6.x packages
    baseurl=https://artifacts.elastic.co/packages/6.x/yum
    gpgcheck=1
    gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
    enabled=1
    autorefresh=1
    type=rpm-md