ELK enterprise-level log analysis system

1. Log management scheme

  • When the number of servers is small, rsyslog or scripts are used to collect and divide logs, and they are unified and summarized to a log server dedicated to storing logs for storage and management.
    (To view the log, you can transfer the required log file to the windows host, and use a professional text tool to open the analysis log)
  • When the number of servers is large, use ELK to collect logs, store logs, and display logs.

1. Why use ELK

  • Logs mainly include system logs, application logs, and security logs. System operation and maintenance and developers can use logs to understand server software and hardware information, check errors in the configuration process and the reasons for errors. Frequent analysis of logs can help you understand the server's load, performance security, and take timely measures to correct errors.
  • Often we can use tools such as grep and awk to analyze the logs of a single machine, but when the logs are scattered and stored on different devices. If you manage dozens or hundreds of servers, you still use the traditional method of logging in to each machine in turn to check the logs. This is cumbersome and inefficient. So we can use centralized log management, such as open source syslog, to collect and summarize logs on all servers. After centralized management of logs, the statistics and retrieval of logs has become a more troublesome thing. Generally, we can use Linux commands such as grep, awk and wc to achieve retrieval and statistics, but for more demanding queries, sorting and statistics, etc. And the huge number of machines is still a bit powerless to use this method.
  • Generally, a large-scale system is a distributed deployment architecture. Different service modules are deployed on different servers. When a problem occurs, in most cases, it is necessary to locate the specific server and service module based on the key information exposed by the problem, and build a set of centralized The log system can improve the efficiency of locating problems.

2. Basic features of complete log system

Collection: Can collect log data from multiple sources
Transmission: Can analyze and filter log data stably and transmit them to the storage system
Storage: Store log data
Analysis: Support UI analysis (that is, web page display)
Warning: Can provide error reports and monitoring mechanisms

2. ELK

1 Introduction

  • The ELK platform is a complete set of log centralized processing solutions, using ElasticSearch (referred to as ES), Logstash and Kiabana three open source tools together to complete more powerful user query, sorting, and statistical requirements for logs.
  • ElasticSearch : It is a distributed storage and retrieval engine developed based on Lucene (a full-text retrieval engine architecture), used to store various logs.
    • Elasticsearch is developed in Java and can communicate with Elasticsearch through a RESTful web interface through a browser. (You can send and transmit some commands through the HTTP protocol to control ES to perform some management operations)
    • Elasticsearch is a real-time, distributed, scalable search engine that allows full-text, structured searches. It is typically used to index and search large volumes of log data, and can also be used to search many different types of documents.
  • Kiabana : Kibana is usually deployed together with Elasticsearch. Kibana is a powerful data visualization Dashboard for Elasticsearch. Kibana provides a graphical web interface to browse Elasticsearch log data, which can be used to summarize, analyze and search for important data.
  • Logstash : as a data collection engine. It supports dynamic collection of data from various data sources, and performs operations such as filtering, analyzing, enriching, and unifying the format on the data, and then stores it in a location specified by the user, and generally sends it to Elasticsearch.
    Logstash is written in Ruby language and runs on Java Virtual Machine (JVM). It is a powerful data processing tool that can realize data transmission, format processing, and format output. Logstash has a powerful plug-in function, which is often used for log processing.
    insert image description here

Other components that can be added:

  • Filebeat: A lightweight open source log file data collector. Usually, Filebeat is installed on the client that needs to collect data, and the directory and log format are specified. Filebeat can quickly collect data and send it to logstash for analysis, or directly to Elasticsearch storage. Compared with logstash running on the JVM in terms of performance It has obvious advantages (Logstash consumes more resources such as memory, CPU, and IO), and it is a replacement for it. Often used in the ELFK architecture.

The benefits of filebeat combined with logstash :

  • 1) Through Logstash has a disk-based adaptive buffering system that will absorb incoming throughput, thus relieving Elasticsearch of the pressure of continuously writing data
  • 2) Pull from other data sources such as databases, S3 object stores, or messaging queues
  • 3) Send data to multiple destinations such as S3, HDFS (Hadoop Distributed File System) or write to a file
  • 4) Use conditional data flow logic to form more complex processing pipelines

Cache/message queue (redis, kafka, RabbitMQ, etc.)

  • Traffic peak clipping and buffering can be performed on high-concurrency log data. Such buffering can protect data from loss to a certain extent, and can also decouple the application of the entire architecture.
    • Application decoupling: For example, if a game wants to update a skin, it needs to stop all services to update. After decoupling, it becomes a skin module, a hero module and some other functional modules. When updating the skin, stop the skin module separately. Updates will not affect the work of other modules.
    • Traffic peak clipping: To clip traffic peaks, the easiest solution to think of is to use message queues to buffer instantaneous traffic, convert synchronous direct calls into asynchronous indirect pushes, and use a queue to undertake instantaneous traffic peaks at one end. Smoothly push messages out on the other end.

2. The workflow of ELK

insert image description here

(1) Deploy Logstash on all servers that need to collect logs; or centralize the management of logs on the log server first, and deploy Logstash on the log server.(It is generally not recommended to deploy Logstash on the application server. It should be because Logstash runs on the JVM, and java applications have high memory requirements, which will affect the memory performance of the application server.)
(2) Logstash collects logs, formats and outputs logs to the Elasticsearch cluster.
(3) Elasticsearch indexes and stores the formatted data.
(4) Kibana queries the data from the ES cluster to generate charts and displays the front-end data.

3. ELK deployment

1. ELK Elasticsearch cluster deployment


node1节点(2C/4G):node1/192.168.80.10					Elasticsearch
node2节点(2C/4G):node2/192.168.80.11					Elasticsearch
Apache节点:apache/192.168.80.12						Logstash  Kibana  Apache


systemctl stop firewalld
setenforce 0
  1. Environmental preparation
#设置Java环境

java -version										#如果没有安装,yum -y install java
openjdk version "1.8.0_131"
OpenJDK Runtime Environment (build 1.8.0_131-b12)
OpenJDK 64-Bit Server VM (build 25.131-b12, mixed mode)

insert image description here

  1. Deploy the Elasticsearch software
(1)安装elasticsearch—rpm包
#上传elasticsearch-6.7.2.rpm到/opt目录下
cd /opt
rpm -ivh elasticsearch-6.7.2.rpm

(2)修改elasticsearch主配置文件
cp /etc/elasticsearch/elasticsearch.yml /etc/elasticsearch/elasticsearch.yml.bak
vim /etc/elasticsearch/elasticsearch.yml
--17--取消注释,指定集群名字
cluster.name: my-elk-cluster
--23--取消注释,指定节点名字:Node1节点为node1,Node2节点为node2
node.name: node1
node.master: true		#是否master节点,false为否
node.data: true			#是否数据节点,false为否
--33--取消注释,指定数据存放路径
path.data: /var/lib/elasticsearch
--37--取消注释,指定日志存放路径
path.logs: /var/log/elasticsearch
--43--取消注释,避免es使用swap交换分区
bootstrap.memory_lock: true
--55--取消注释,设置监听地址,0.0.0.0代表所有地址
network.host: 0.0.0.0
--59--取消注释,ES 服务的默认监听端口为9200
http.port: 9200					#指定es集群提供外部访问的接口
transport.tcp.port: 9300		#指定es集群内部通信接口
--68--取消注释,集群发现通过单播实现,指定要发现的节点
discovery.zen.ping.unicast.hosts: ["192.168.80.10:9300", "192.168.80.11:9300"]

grep -v "^#" /etc/elasticsearch/elasticsearch.yml

(3)es 性能调优参数
#优化最大内存大小和最大文件描述符的数量
vim /etc/security/limits.conf
......
*  soft    nofile          65536
*  hard    nofile          65536
*  soft    nproc           32000
*  hard    nproc           32000
*  soft    memlock         unlimited
*  hard    memlock         unlimited

vim /etc/systemd/system.conf
DefaultLimitNOFILE=65536
DefaultLimitNPROC=32000
DefaultLimitMEMLOCK=infinity

需重启生效

#优化elasticsearch用户拥有的内存权限
由于ES构建基于lucene, 而lucene设计强大之处在于lucene能够很好的利用操作系统内存来缓存索引数据,以提供快速的查询性能。lucene的索引文件segements是存储在单文件中的,并且不可变,对于OS来说,能够很友好地将索引文件保持在cache中,以便快速访问;因此,我们很有必要将一半的物理内存留给lucene ; 另一半的物理内存留给ES(JVM heap )。所以, 在ES内存设置方面,可以遵循以下原则:
1.当机器内存小于64G时,遵循通用的原则,50%给ES,50%留给操作系统,供lucene使用
2.当机器内存大于64G时,遵循原则:建议分配给ES分配 4~32G 的内存即可,其它内存留给操作系统,供lucene使用

vim /etc/sysctl.conf
#一个进程可以拥有的最大内存映射区域数,参考数据(分配 2g/262144,4g/4194304,8g/8388608)
vm.max_map_count=262144

sysctl -p
sysctl -a | grep vm.max_map_count

(4)启动elasticsearch是否成功开启
systemctl start elasticsearch.service
systemctl enable elasticsearch.service
netstat -antp | grep 9200

(5)查看节点信息
浏览器访问  http://192.168.80.10:9200  、 http://192.168.80.11:9200 查看节点 Node1、Node2 的信息。

浏览器访问 http://192.168.80.10:9200/_cluster/health?pretty  、 http://192.168.80.11:9200/_cluster/health?pretty查看群集的健康情况,可以看到 status 值为 green(绿色), 表示节点健康运行。

浏览器访问 http://192.168.80.10:9200/_cluster/state?pretty  检查群集状态信息。

#使用上述方式查看群集的状态对用户并不友好,可以通过安装 Elasticsearch-head 插件,可以更方便地管理群集。

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

insert image description hereinsert image description here
insert image description here
insert image description here

insert image description here

  1. Install the Elasticsearch-head plugin
Elasticsearch 在 5.0 版本后,Elasticsearch-head 插件需要作为独立服务进行安装,需要使用npm工具(NodeJS的包管理工具)安装。
安装 Elasticsearch-head 需要提前安装好依赖软件 node 和 phantomjs。
node:是一个基于 Chrome V8 引擎的 JavaScript 运行环境。
phantomjs:是一个基于 webkit 的JavaScriptAPI,可以理解为一个隐形的浏览器,任何基于 webkit 浏览器做的事情,它都可以做到。

(1)编译安装 node
#上传软件包 node-v8.2.1.tar.gz 到/opt
yum install gcc gcc-c++ make -y

cd /opt
tar zxvf node-v8.2.1.tar.gz

cd node-v8.2.1/
./configure
make && make install

(2)安装 phantomjs
#上传软件包 phantomjs-2.1.1-linux-x86_64.tar.bz2 到
cd /opt
tar jxvf phantomjs-2.1.1-linux-x86_64.tar.bz2
cd /opt/phantomjs-2.1.1-linux-x86_64/bin
cp phantomjs /usr/local/bin

(3)安装 Elasticsearch-head 数据可视化工具
#上传软件包 elasticsearch-head-master.zip 到/opt
cd /opt
unzip elasticsearch-head-master.zip
cd /opt/elasticsearch-head/
npm install		 //安装依赖包

(4)修改 Elasticsearch 主配置文件
vim /etc/elasticsearch/elasticsearch.yml
......
--末尾添加以下内容--
http.cors.enabled: true				#开启跨域访问支持,默认为 false
http.cors.allow-origin: "*"			#指定跨域访问允许的域名地址为所有

systemctl restart elasticsearch

(5)启动 elasticsearch-head 服务
#必须在解压后的 elasticsearch-head 目录下启动服务,进程会读取该目录下的 gruntfile.js 文件,否则可能启动失败。
cd /usr/local/src/elasticsearch-head/
npm run start &

> [email protected] start /usr/local/src/elasticsearch-head
> grunt server

Running "connect:server" (connect) task
Waiting forever...
Started connect web server on http://localhost:9100

#elasticsearch-head 监听的端口是 9100
netstat -natp |grep 9100

(6)通过 Elasticsearch-head 查看 Elasticsearch 信息
通过浏览器访问 http://192.168.80.10:9100/ 地址并连接群集。如果看到群集健康值为 green 绿色,代表群集很健康。

(7)插入索引
#通过命令插入一个测试索引,索引为 index-demo,类型为 test。
curl -X PUT 'localhost:9200/index-demo/test/1?pretty&pretty' -H 'content-Type: application/json' -d '{"user":"zhangsan","mesg":"hello world"}'
//输出结果如下:
{
    
    
"_index" : "index-demo",
"_type" : "test",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
    
    
"total" : 2,
"successful" : 2,
"failed" : 0
},
"created" : true
}

Visit http://192.168.80.10:9100/ with a browser to view the index information, and you can see that the index is divided into 5 fragments by default, and there is a copy.
Click "Data Browse", you will find the index created on node1 as index-demo, and the related information of type test.
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

2. ELK Logstash deployment

Logstash is generally deployed on servers whose logs need to be monitored. In this case, Logstash is deployed on the Apache server to collect the log information of the Apache server and send it to Elasticsearch.

  1. change hostname
hostnamectl set-hostname apache

insert image description here

  1. Install Apache service (httpd)
yum -y install httpd
systemctl start httpd

insert image description here

  1. Install the Java environment
yum -y install java
java -version

insert image description here

  1. install logstash
#上传软件包 logstash-6.7.2.rpm 到/opt目录下
cd /opt
rpm -ivh logstash-6.7.2.rpm                          
systemctl start logstash.service                      
systemctl enable logstash.service

ln -s /usr/share/logstash/bin/logstash /usr/local/bin/
  1. Test Logstash
Logstash 命令常用选项:
-f:通过这个选项可以指定 Logstash 的配置文件,根据配置文件配置 Logstash 的输入和输出流。
-e:从命令行中获取,输入、输出后面跟着字符串,该字符串可以被当作 Logstash 的配置(如果是空,则默认使用 stdin 作为输入,stdout 作为输出)。
-t:测试配置文件是否正确,然后退出。

定义输入和输出流:
#输入采用标准输入,输出采用标准输出(类似管道),新版本默认使用 rubydebug 格式输出
logstash -e 'input { stdin{} } output { stdout{} }'

#使用 rubydebug 输出详细格式显示,codec 为一种编解码器
logstash -e 'input { stdin{} } output { stdout{ codec=>rubydebug } }'
......
www.baidu.com										#键入内容(标准输入)
{
    
    
    "@timestamp" => 2020-12-22T02:15:39.136Z,		#输出结果(标准输出处理后的结果)
      "@version" => "1",
          "host" => "apache",
       "message" => "www.baidu.com"
}

#使用 Logstash 将信息写入 Elasticsearch 中
logstash -e 'input { stdin{} } output { elasticsearch { hosts=>["192.168.80.10:9200"] } }'
			 输入				输出			对接
......
www.baidu.com										#键入内容(标准输入)
www.sina.com.cn										#键入内容(标准输入)
www.google.com										#键入内容(标准输入)

//结果不在标准输出显示,而是发送至 Elasticsearch 中,可浏览器访问 http://192.168.80.10:9100/ 查看索引信息和数据浏览。

insert image description hereinsert image description here
insert image description here

insert image description here
insert image description here

  1. Define the logstash configuration file
Logstash 配置文件基本由三部分组成:input、output 以及 filter(可选,根据需要选择使用)。
●input:表示从数据源采集数据,常见的数据源如Kafka、日志文件等
file   beats   kafka   redis   stdin

●filter:表示数据处理层,包括对数据进行格式化处理、数据类型转换、数据过滤等,支持正则表达式
grok       对若干个大文本字段进行再分割成一些小字段   (?<字段名>正则表达式)   字段名: 正则表达式匹配到的内容
date       对数据中的时间格式进行统一和格式化
mutate     对一些无用的字段进行剔除,或增加字段
mutiline   对多行数据进行统一编排,多行合并或拆分

●output:表示将Logstash收集的数据经由过滤器处理之后输出到Elasticsearch。
elasticsearch   stdout 

#格式如下:
input {
    
    ...}
filter {
    
    ...}
output {
    
    ...}

#在每个部分中,也可以指定多个访问方式。例如,若要指定两个日志来源文件,则格式如下:
input {
    
    
	file {
    
     path =>"/var/log/messages" type =>"syslog"}
	file {
    
     path =>"/var/log/httpd/access.log" type =>"apache"}
}

#修改 Logstash 配置文件,让其收集系统日志/var/log/messages,并将其输出到 elasticsearch 中。
chmod +r /var/log/messages					#让 Logstash 可以读取日志

cd /etc/logstash/conf.d/
vim system.conf
input {
    
    
    file{
    
    
        path =>"/var/log/messages"
        type =>"system"
        start_position =>"beginning"
		# ignore_older => 604800
        sincedb_path => "/etc/logstash/sincedb_path/log_progress"
        add_field => {
    
    "log_hostname"=>"${
     
     HOSTNAME}"}
    }
}
#path表示要收集的日志的文件位置
#type是输入ES时给结果增加一个叫type的属性字段
#start_position可以设置为beginning或者end,beginning表示从头开始读取文件,end表示读取最新的,这个要和ignore_older一起使用
#ignore_older表示了针对多久的文件进行监控,默认一天,单位为秒,可以自己定制,比如默认只读取一天内被修改的文件
#sincedb_path表示文件读取进度的记录,每行表示一个文件,每行有两个数字,第一个表示文件的inode,第二个表示文件读取到的位置(byteoffset)。默认为$HOME/.sincedb*
#add_field增加属性。这里使用了${HOSTNAME},即本机的环境变量,如果要使用本机的环境变量,那么需要在启动命令上加--alow-env

output {
    
    
    elasticsearch {
    
    												#输出到 elasticsearch
        hosts => ["192.168.80.10:9200","192.168.80.11:9200"]	#指定 elasticsearch 服务器的地址和端口
        index =>"system-%{+YYYY.MM.dd}"							#指定输出到 elasticsearch 的索引格式
    }
}

mkdir /etc/logstash/sincedb_path/
touch /etc/logstash/sincedb_path/log_progress
chown logstash:logstash /etc/logstash/sincedb_path/log_progress

logstash -f system.conf

Browser access http://192.168.80.10:9100/ to view index information

insert image description here
insert image description here

insert image description here
insert image description here

insert image description here

3, ELK Kiabana Department

  1. Install Kiabana
#上传软件包 kibana-6.7.2-x86_64.rpm 到/opt目录
cd /opt
rpm -ivh kibana-6.7.2-x86_64.rpm

insert image description here

  1. Set up Kibana's main configuration file
vim /etc/kibana/kibana.yml
--2--取消注释,Kiabana 服务的默认监听端口为5601
server.port: 5601
--7--取消注释,设置 Kiabana 的监听地址,0.0.0.0代表所有地址
server.host: "0.0.0.0"
--28--取消注释,配置es服务器的ip,如果是集群则配置该集群中master节点的ip
elasticsearch.url:  ["http://192.168.80.10:9200","http://192.168.80.11:9200"] 
--37--取消注释,设置在 elasticsearch 中添加.kibana索引
kibana.index: ".kibana"
--96--取消注释,配置kibana的日志文件路径(需手动创建),不然默认是messages里记录日志
logging.dest: /var/log/kibana.log
  1. Create a log file and start the Kibana service
touch /var/log/kibana.log
chown kibana:kibana /var/log/kibana.log

systemctl start kibana.service
systemctl enable kibana.service

netstat -natp | grep 5601
  1. Verify Kibana
浏览器访问 http://192.168.80.10:5601
第一次登录需要添加一个 Elasticsearch 索引:
Management -> Index Pattern -> Create index pattern
Index pattern 输入:system-*	#在索引名中输入之前配置的 Output 前缀“system”

Next step -> Time Filter field name 选择 @timestamp -> Create index pattern

单击 “Discover” 按钮可查看图表信息及日志信息。
数据展示可以分类显示,在“Available Fields”中的“host”,然后单击 “add”按钮,可以看到按照“host”筛选后的结果

insert image description here
insert image description here

  1. Add Apache server logs (accessed, errors) to Elasticsearch and display them via Kibana
vim /etc/logstash/conf.d/apache_log.conf
input {
    
    
    file{
    
    
        path => "/etc/httpd/logs/access_log"
        type => "access"
        start_position => "beginning"
    }
    file{
    
    
        path => "/etc/httpd/logs/error_log"
        type => "error"
        start_position => "beginning"
    }
}
output {
    
    
    if [type] == "access" {
    
    
        elasticsearch {
    
    
            hosts => ["192.168.80.10:9200","192.168.80.11:9200"]
            index => "apache_access-%{+YYYY.MM.dd}"
        }
    }
	if [type] == "error" {
    
    
        elasticsearch {
    
    
            hosts => ["192.168.80.10:9200","192.168.80.11:9200"]
            index => "apache_error-%{+YYYY.MM.dd}"
        }
    }
}

cd /etc/logstash/conf.d/
/usr/share/logstash/bin/logstash -f apache_log.conf

浏览器访问 http://192.168.80.10:9100 查看索引是否创建

Access http://192.168.80.10:5601 in the browser to log in to Kibana, click the "Index Pattern -> Create Index Pattern" button to add an index, enter the output prefix apache_access- previously configured in the index name, and click the "Create" button . Add the apache_error-index in the same way .
Select the "Discover" tab, and select the newly added apache_access-
and apache_error-
indexes in the middle drop-down list to view the corresponding charts and log information.
insert image description here
insert image description here
insert image description here

4. Filebeat+ELK deployment

Node1节点(2C/4G):node1/192.168.80.10					Elasticsearch
Node2节点(2C/4G):node2/192.168.80.11					Elasticsearch
Apache节点:apache/192.168.80.12						Logstash  Kibana  Apache
Filebeat节点:filebeat/192.168.80.13					Filebeat
  1. Install Filebeat
#上传软件包 filebeat-6.7.2-linux-x86_64.tar.gz 到/opt目录
tar zxvf filebeat-6.7.2-linux-x86_64.tar.gz
mv filebeat-6.7.2-linux-x86_64/ /usr/local/filebeat
  1. Set up filebeat's main configuration file
cd /usr/local/filebeat

vim filebeat.yml
filebeat.inputs:
- type: log         #指定 log 类型,从日志文件中读取消息
  enabled: true
  paths:
    - /var/log/messages       #指定监控的日志文件
    - /var/log/*.log
  tags: ["sys"]		#设置索引标签
  fields:           #可以使用 fields 配置选项设置一些参数字段添加到 output 中
    service_name: filebeat
    log_type: syslog
    from: 192.168.80.13

--------------Elasticsearch output-------------------
(全部注释掉)

----------------Logstash output----------------------
output.logstash:
  hosts: ["192.168.80.12:5044"]      #指定 logstash 的 IP 和端口

#启动 filebeat
nohup ./filebeat -e -c filebeat.yml > filebeat.out &
#-e:输出到标准输出,禁用syslog/文件输出
#-c:指定配置文件
#nohup:在系统后台不挂断地运行命令,退出终端不会影响程序的运行
  1. Create a new Logstash configuration file on the node where the Logstash component is located
cd /etc/logstash/conf.d

vim filebeat.conf
input {
    
    
    beats {
    
    
        port => "5044"
    }
}

#filebeat发送给logstash的日志内容会放到message字段里面,logstash使用grok插件正则匹配message字段内容进行字段分割
#Kibana自带grok的正则匹配的工具:http://<your kibana IP>:5601/app/kibana#/dev_tools/grokdebugger
# %{IPV6}|%{IPV4} 为 logstash 自带的 IP 常量
filter {
    
    
  grok {
    
    
    match => ["message", "(?<remote_addr>%{IPV6}|%{IPV4})[\s\-]+\[(?<logTime>.*)\]\s+\"(?<method>\S+)\s+(?<url_path>.+)\"\s+(?<rev_code>\d+) \d+ \"(?<req_addr>.+)\" \"(?<content>.*)\""]
  }
}

output {
    
    
    elasticsearch {
    
    
        hosts => ["192.168.80.10:9200","192.168.80.11:9200"]
        index => "%{[fields][service_name]}-%{+YYYY.MM.dd}"
    }
    stdout {
    
    
        codec => rubydebug
    }
}

#启动 logstash
logstash -f filebeat.conf
  1. Access http://192.168.80.10:5601 with a browser to log in to Kibana, click the "Create Index Pattern" button to add the index "filebeat-*", click the "create" button to create, click the "Discover" button to view the chart information and log information.

insert image description here

insert image description here

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/m0_74412260/article/details/131634354