大数据运维之日志管理——ELK+beat搭建

文章目录

    • 1.场景
    • 2.组件
    • 3.流程
    • 4.安装FileBeat
    • 5.安装Logstash
    • 6.搭建ElasticSearch集群
    • 6.安装kibana

1.场景

在开发项目时,我们可能开发很多程序,或者使用很多sparktask处理数据等等,在多个服务器上产生很多个日志文件,在需要查看日志或者排错时,如果去服务器上查看会非常繁琐。

2.组件

E——ElasticSearch
L——Logstash
K——Kibana
可以使用户Logstash直接监控日志文件,然后写入到ElasticSearch,但是由于我们需要编写Logstash中的filter来对日志进行操作,所以这样用起来很不方便,再有就是Logstash并不是轻量级别的,所以我们引入更轻量的Beat中的FileBeat来监控日志文件。

3.流程

大数据运维之日志管理——ELK+beat搭建_第1张图片

4.安装FileBeat

1)下载tar包(地址):

https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-6.4.2-linux-x86_64.tar.gz

2)解压并编辑配置文件

tar -xvf filebeat-6.4.2-linux-x86_64.tar.gz
cd filebeat-6.4.2
vim filebeat.yml

配置监控文件Filebeat inputs,为自己想要监控的文件
FileBeat默认直接写入ES,我们不需要,在配置文件Elasticsearch output 处将其注释掉
修改Logstash output部分配置,使其将数据发送到logstash


#=========================== Filebeat inputs =============================

filebeat.inputs:

# Each - is an input. Most options can be set at the input level, so
# you can use different inputs for various configurations.
# Below are the input specific configurations.

- type: log

  # Change to true to enable this input configuration.
  # enabled: false

  enabled: true
  # Paths that should be crawled and fetched. Glob based paths.
  paths:
    # - /var/log/*.log
   	#日志路径
    - /var/.../*.log
    #- c:\programdata\elasticsearch\logs\*

  # Exclude lines. A list of regular expressions to match. It drops the lines that are
  # matching any regular expression from the list.
  #exclude_lines: ['^DBG']

  # Include lines. A list of regular expressions to match. It exports the lines that are
  # matching any regular expression from the list.
  #include_lines: ['^ERR', '^WARN']

  # Exclude files. A list of regular expressions to match. Filebeat drops the files that
  # are matching any regular expression from the list. By default, no files are dropped.
  #exclude_files: ['.gz$']

  # Optional additional fields. These fields can be freely picked
  # to add additional information to the crawled log files for filtering
  #fields:
  #  level: debug
  #  review: 1

  ### Multiline options

  # Multiline can be used for log messages spanning multiple lines. This is common
  # for Java Stack Traces or C-Line Continuation

  # The regexp Pattern that has to be matched. The example pattern matches all lines starting with [
  #multiline.pattern: ^\[

  # Defines if the pattern set under pattern should be negated or not. Default is false.
  #multiline.negate: false

  # Match can be set to "after" or "before". It is used to define if lines should be append to a pattern
  # that was (not) matched before or after or as long as a pattern is not matched based on negate.
  # Note: After is the equivalent to previous and before is the equivalent to to next in Logstash
  #multiline.match: after


#============================= Filebeat modules ===============================

filebeat.config.modules:
  # Glob pattern for configuration loading
  path: ${path.config}/modules.d/*.yml

  # Set to true to enable config reloading
  reload.enabled: false

  # Period on which files under path should be checked for changes
  #reload.period: 10s

#==================== Elasticsearch template setting ==========================

#setup.template.settings:
#  index.number_of_shards: 3
  #index.codec: best_compression
  #_source.enabled: false

#================================ General =====================================

# The name of the shipper that publishes the network data. It can be used to group
# all the transactions sent by a single shipper in the web interface.
#name:

# The tags of the shipper are included in their own field with each
# transaction published.
#tags: ["service-X", "web-tier"]

# Optional fields that you can specify to add additional information to the
# output.
#fields:
#  env: staging


#============================== Dashboards =====================================
# These settings control loading the sample dashboards to the Kibana index. Loading
# the dashboards is disabled by default and can be enabled either by setting the
# options here, or by using the `-setup` CLI flag or the `setup` command.
#setup.dashboards.enabled: false

# The URL from where to download the dashboards archive. By default this URL
# has a value which is computed based on the Beat name and version. For released
# versions, this URL points to the dashboard archive on the artifacts.elastic.co
# website.
#setup.dashboards.url:

#============================== Kibana =====================================

# Starting with Beats version 6.0.0, the dashboards are loaded via the Kibana API.
# This requires a Kibana endpoint configuration.
setup.kibana:

  # Kibana Host
  # Scheme and port can be left out and will be set to the default (http and 5601)
  # In case you specify and additional path, the scheme is required: http://localhost:5601/path
  # IPv6 addresses should always be defined as: https://[2001:db8::1]:5601
  #host: "localhost:5601"

#============================= Elastic Cloud ==================================

# These settings simplify using filebeat with the Elastic Cloud (https://cloud.elastic.co/).

# The cloud.id setting overwrites the `output.elasticsearch.hosts` and
# `setup.kibana.host` options.
# You can find the `cloud.id` in the Elastic Cloud web UI.
#cloud.id:

# The cloud.auth setting overwrites the `output.elasticsearch.username` and
# `output.elasticsearch.password` settings. The format is `:`.
#cloud.auth:

#================================ Outputs =====================================

# Configure what output to use when sending the data collected by the beat.

#-------------------------- Elasticsearch output ------------------------------
#output.elasticsearch:
  # Array of hosts to connect to.
#  hosts: ["localhost:9200"]

  # Optional protocol and basic auth credentials.
  #protocol: "https"
  #username: "elastic"
  #password: "changeme"

#----------------------------- Logstash output --------------------------------
output.logstash:
  # The Logstash hosts
  hosts: ["logstash:5044"]

  # Optional SSL. By default is off.
  # List of root certificates for HTTPS server verifications
  #ssl.certificate_authorities: ["/etc/pki/root/ca.pem"]

  # Certificate for SSL client authentication
  #ssl.certificate: "/etc/pki/client/cert.pem"

  # Client Certificate Key
  #ssl.key: "/etc/pki/client/cert.key"

#================================ Logging =====================================

# Sets log level. The default log level is info.
# Available log levels are: error, warning, info, debug
#logging.level: debug

# At debug level, you can selectively enable logging only for some components.
# To enable all selectors use ["*"]. Examples of other selectors are "beat",
# "publish", "service".
#logging.selectors: ["*"]

#============================== Xpack Monitoring ===============================
# filebeat can export internal metrics to a central Elasticsearch monitoring
# cluster.  This requires xpack monitoring to be enabled in Elasticsearch.  The
# reporting is disabled by default.

# Set to true to enable the monitoring reporter.
#xpack.monitoring.enabled: false

# Uncomment to send the metrics to Elasticsearch. Most settings from the
# Elasticsearch output are accepted here as well. Any setting that is not set is
# automatically inherited from the Elasticsearch output configuration, so if you
# have the Elasticsearch output configured, you can simply uncomment the
# following line.
#xpack.monitoring.elasticsearch:

启动命令nohup ./filebeat -e -c filebeat.yml &

5.安装Logstash

1)下载tar包(地址):

https://artifacts.elastic.co/downloads/logstash/logstash-6.4.2.tar.gz

2)解压并编辑配置文件

tar -xvf logstash-6.4.2.tar.gz
cd logstash-6.4.2
#自己写一个配置文件 名字随便
vim test.conf

input部分端口应和filebeat配置端口一致
output配置elasticsearch的ip和端口
主要编写filter部分,支持grok正则,我这里使用ruby插件编写的

input {
    beats {
        port => 5044
    }
}

filter {
# 我的日志内容如下
# [loglevel][2020-04-21:14:37:06][thread],class,msg!
# logstash 把每条数据看作一个event以json格式传输,会包含很多字段
#["message","prospector","input","tags","host","@timestamp","source","beat","@version","offset"] 等等
# 其中 message 的值为我们传输的日志内容
        ruby {
        
                 code => "		# 日志信息会包装到message字段中 首先按照‘,’切分
                                arr1=event.get('message').split(',')
                                # 得到如下
                                # arr1[0]=[loglevel][2020-04-21:14:37:06][thread]
                                # arr1[1]=class
                                # arr1[2]=msg
                              
                                event.set('message1',arr1[1])
                                event.set('message2',arr1[2])
                                # 处理数据中的'[' (删掉)
                                msg=arr1[0].gsub('[','')
                                # 处理数据中的']' (替换为‘,’)
                                ms1=msg.gsub(']',',')
                                # 按照‘,’ 拆分
                                arr2=ms1.split(',')
                                # arr2[0]=loglevel
                                # arr2[1]=2020-04-21:14:37:06
                                # arr2[2]=thread
                                event.set('loglevel',arr2[0])
                                event.set('date',arr2[1])
                                event.set('thread',arr2[2])"
# 删除多余不用字段
                 remove_field => ["message","prospector","input","tags","host","@timestamp","source","beat","@version","offset"]

           }
}
output {
        elasticsearch{
                hosts=>["es1:9200","es2:9200","es3:9200"]
                index=>"test_index"
        }

}

filter之后的数据结果为

{
        "date" => "2020-04-21:14:37:06",
    "loglevel" => "loglevel",
      "thread" => "thread",
    "message2" => "msg",
    "message1" => "class"
}

启动命令bin/logstash -f fpc-log.conf &

6.搭建ElasticSearch集群

1)下载tar包(地址):

https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.4.2.tar.gz

2)解压并编辑配置文件

tar -xvf elasticsearch-6.4.2.tar.gz
cd elasticsearch-6.4.2/config
mv elasticsearch.yml elasticsearch.yml.bak
vim elasticsearch.yml
	#设置ES集群名称
	cluster.name: cluster-name
	node.name: node-name
	#path.data: /var/lib/elasticsearch
	#path.logs: /var/log/elasticsearch
	bootstrap.memory_lock: true
	bootstrap.system_call_filter: false
	network.host: 10.10.151.24
	discovery.zen.ping.unicast.hosts: ["ip1","ip2","ip3"]
	discovery.zen.minimum_master_nodes: 2
	http.cors.enabled: true
	http.cors.allow-origin: "*"

3)把 elasticsearch-6.4.2/ 传到另外两个服务器上,并修改elasticsearch.yml中的node.name:为对应的node-name
4)ES不允许root用户操作(三台机器都操作)

groupaddes          						#增加es组
useraddes -g es -p pwd          			#增加es用户并附加到es组
chown -Res:es elasticsearch-6.4.2         	#给目录权限

启动命令为su - es -c '/opt/elasticsearch-6.2.4/bin/elasticsearch -d'
访问ip:9200/_cat/health?v
在这里插入图片描述
status为green代表安装成功

6.安装kibana

1)下载tar包(地址):

https://artifacts.elastic.co/downloads/kibana/kibana-6.4.2-linux-x86_64.tar.gz

2)解压并编辑配置文件

tar -xvf  kibana-6.4.2-linux-x86_64
vim kibana-6.4.2-linux-x86_64/config/kibana.yml 
# 在最后添加
server.port: 5601
server.host: "0.0.0.0"
elasticsearch.url: "http://esip:9200"
kibana.index: ".kibana"

启动命令nohup bin/kibana &

可访问ip:5601查看

你可能感兴趣的:(linux,logstash,es)