ELK搭建 日志可视化(全过程)

本文详细介绍了ELK(Elasticsearch,Logstash,Kibana)组件在公司项目中三级等保评审中的应用,涉及版本一致性、Java环境设置、ES和Kibana的安装与配置,以及常见启动错误的解决方案。
摘要由CSDN通过智能技术生成

场景:公司项目参与三级等保评审,有很多安全方面的要求,比如密码安全等级、脱敏、数据库主从备份、灾备等。其中就包括“日志可视化”,今天先从最简单的日志可视化开始

ELK解释:Elasticsearch , Logstash, Kibana , 它们都是开源软件,具体功能网上有详解,我只做简单描述,主要上干货。
    Elasticsearch:简称es,可存储数据,存储索引
    Logstash :主要负责将各条业务线的各类日志统一收集、过滤后,输出给 Elasticsearch(创建索引到es中) 进行下一步处理
    Kibana  : 读取es中的索引,展示索引详情,展示以索引为基础组合而成的图表、仪表盘

一,版本必须一致

二,确定java已安装,至少是1.8的。查看命令:

----------------------------------------------------------- ES 安装 -----------------------------------------------------------
1,先解压es。去到文件路径下,查看

解压命令

tar -zxvf elasticsearch-7.17.0-linux-x86_64.tar.gz 

2,解压后,修改 config 下面的配置文件 elasticsearch.yml

# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
#       Before you set out to tweak and tune the configuration, make sure you
#       understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
#cluster.name: my-application
# 集群名称
cluster.name: elasticsearch-01
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
node.name: node1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
#path.data: /path/to/data
#
# Path to log files:
#
#path.logs: /path/to/logs
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
bootstrap.memory_lock: false
bootstrap.system_call_filter: false
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# By default Elasticsearch is only accessible on localhost. Set a different
# address here to expose this node on the network:
#

network.host: 0.0.0.0
#
# By default Elasticsearch listens for HTTP traffic on the first free port it
# finds starting at 9200. Set a specific HTTP port here:
#
#http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when this node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
#discovery.seed_hosts: ["host1", "host2"]
#
# Bootstrap the cluster using an initial set of master-eligible nodes:
#
#cluster.initial_master_nodes: ["node-1", "node-2"]
cluster.initial_master_nodes: ["node1"]
#
# For more information, consult the discovery and cluster formation module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Require explicit names when deleting indices:
#
#action.destructive_requires_name: true
#
# ---------------------------------- Security ----------------------------------
#
#                                 *** WARNING ***
#
# Elasticsearch security features are not enabled by default.
# These features are free, but require configuration changes to enable them.
# This means that users don’t have to provide credentials and can get full access
# to the cluster. Network connections are also not encrypted.
#
# To protect your data, we strongly encourage you to enable the Elasticsearch security features. 
# Refer to the following documentation for instructions.
#
# https://www.elastic.co/guide/en/elasticsearch/reference/7.16/configuring-stack-security.html
# 支持跨域
http.cors.enabled: true
http.cors.allow-origin: "*"

3,运行es,命令

/data/elk/elasticsearch-7.17.0/bin/elasticsearch

4,查看es,如果运行成功,浏览器输入ip:9200,显示如下则说明成功

----------------------------------------------------------- ES 启动时常见错误 -----------------------------------------------------------

一般情况下,启动es会遇到以下几个错误:【错误1:linux不能以root身份启动es】报错信息如下:

could not find java in bundled jdk at /opt/elasticsearch/elasticsearch-7.9.1/jdk/bin/java

那么就需要新建用户,以新用户来启动。解决方案:

1,以root身份,创建新用户 user_es

sudo adduser user_es

2,以root身份,设置密码    

sudo passwd user_es

回车 会提示输入两次密码

3,以root身份,对该 user_es 目录进行授权 命令:

sudo chown -R user_es:user_es /opt/elasticsearch/elasticsearch-7.9.1

4,切换到 user_es 账户下 启动es:命令和之前一样

5,查看es运行状态

ps -ef|grep elasticsearch

6,运行成功

一般情况下,启动es会遇到以下几个错误:【错误2:ES的安全机制问题】报错信息如下:

Native controller process has stopped - no new native processes can be started

产生这个问题的原因是因为ES的安全机制问题,解决方案:

root身份登录并操作:

找到文件 /etc/security/limits.conf,修改为

aa(你的非root用户名) soft nofile 65536
aa(你的非root用户名) hard nofile 65536
aa(你的非root用户名) soft nproc 4096
aa(你的非root用户名) hard nproc 4096

再找到文件 /etc/security/limits.d,修改里面的配置文件

##这两行是原本的内容
*          soft    nproc     4096
root       soft    nproc     unlimited


#将*号改成用户名
aa(你的非root用户名)   soft    nproc     4096
root       soft    nproc     unlimited

再找到 /etc/sysctl.conf ,在最后一行增加

vm.max_map_count = 655360

root身份下 执行命令

sysctl -p

至此,es可以成功启动了

----------------------------------------------------------- kibana安装 -----------------------------------------------------------

1,解压kibana

tar -zxvf kibana-7.17.0-linux-x86_64.tar.gz 

2,修改 config 里的配置文件 kibana.yml

# Kibana is served by a back end server. This setting specifies the port to use.
#server.port: 5601

# Specifies the address to which the Kibana server will bind. IP addresses and host names are both valid values.
# The default is 'localhost', which usually means remote machines will not be able to connect.
# To allow connections from remote users, set this parameter to a non-loopback address.
server.host: "192.168.111.111"

# Enables you to specify a path to mount Kibana at if you are running behind a proxy.
# Use the `server.rewriteBasePath` setting to tell Kibana if it should remove the basePath
# from requests it receives, and to prevent a deprecation warning at startup.
# This setting cannot end in a slash.
#server.basePath: ""

# Specifies whether Kibana should rewrite requests that are prefixed with
# `server.basePath` or require that they are rewritten by your reverse proxy.
# This setting was effectively always `false` before Kibana 6.3 and will
# default to `true` starting in Kibana 7.0.
#server.rewriteBasePath: false

# Specifies the public URL at which Kibana is available for end users. If
# `server.basePath` is configured this URL should end with the same basePath.
#server.publicBaseUrl: ""

# The maximum payload size in bytes for incoming server requests.
#server.maxPayload: 1048576

# The Kibana server's name.  This is used for display purposes.
#server.name: "your-hostname"

# The URLs of the Elasticsearch instances to use for all your queries.
elasticsearch.hosts: ["http://192.168.111.111:9200"]

# Kibana uses an index in Elasticsearch to store saved searches, visualizations and
# dashboards. Kibana creates a new index if the index doesn't already exist.
#kibana.index: ".kibana"

# The default application to load.
#kibana.defaultAppId: "home"

# If your Elasticsearch is protected with basic authentication, these settings provide
# the username and password that the Kibana server uses to perform maintenance on the Kibana
# index at startup. Your Kibana users still need to authenticate with Elasticsearch, which
# is proxied through the Kibana server.
#elasticsearch.username: "kibana_system"
#elasticsearch.password: "pass"

# Kibana can also authenticate to Elasticsearch via "service account tokens".
# If may use this token instead of a username/password.
# elasticsearch.serviceAccountToken: "my_token"

# Enables SSL and paths to the PEM-format SSL certificate and SSL key files, respectively.
# These settings enable SSL for outgoing requests from the Kibana server to the browser.
#server.ssl.enabled: false
#server.ssl.certificate: /path/to/your/server.crt
#server.ssl.key: /path/to/your/server.key

# Optional settings that provide the paths to the PEM-format SSL certificate and key files.
# These files are used to verify the identity of Kibana to Elasticsearch and are required when
# xpack.security.http.ssl.client_authentication in Elasticsearch is set to required.
#elasticsearch.ssl.certificate: /path/to/your/client.crt
#elasticsearch.ssl.key: /path/to/your/client.key

# Optional setting that enables you to specify a path to the PEM file for the certificate
# authority for your Elasticsearch instance.
#elasticsearch.ssl.certificateAuthorities: [ "/path/to/your/CA.pem" ]

# To disregard the validity of SSL certificates, change this setting's value to 'none'.
#elasticsearch.ssl.verificationMode: full

# Time in milliseconds to wait for Elasticsearch to respond to pings. Defaults to the value of
# the elasticsearch.requestTimeout setting.
#elasticsearch.pingTimeout: 1500

# Time in milliseconds to wait for responses from the back end or Elasticsearch. This value
# must be a positive integer.
#elasticsearch.requestTimeout: 30000

# List of Kibana client-side headers to send to Elasticsearch. To send *no* client-side
# headers, set this value to [] (an empty list).
#elasticsearch.requestHeadersWhitelist: [ authorization ]

# Header names and values that are sent to Elasticsearch. Any custom headers cannot be overwritten
# by client-side headers, regardless of the elasticsearch.requestHeadersWhitelist configuration.
#elasticsearch.customHeaders: {}

# Time in milliseconds for Elasticsearch to wait for responses from shards. Set to 0 to disable.
#elasticsearch.shardTimeout: 30000

# Logs queries sent to Elasticsearch. Requires logging.verbose set to true.
#elasticsearch.logQueries: false

# Specifies the path where Kibana creates the process ID file.
#pid.file: /run/kibana/kibana.pid

# Enables you to specify a file where Kibana stores log output.
#logging.dest: stdout

# Set the value of this setting to true to suppress all logging output.
#logging.silent: false

# Set the value of this setting to true to suppress all logging output other than error messages.
#logging.quiet: false

# Set the value of this setting to true to log all events, including system usage information
# and all requests.
#logging.verbose: false

# Set the interval in milliseconds to sample system and process performance
# metrics. Minimum is 100ms. Defaults to 5000.
#ops.interval: 5000

# Specifies locale to be used for all localizable strings, dates and number formats.
# Supported languages are the following: English - en , by default , Chinese - zh-CN .
i18n.locale: "zh-CN"

3,运行kibana

/data/elk/kibana-7.17.0-linux-x86_64/bin/kibana --allow-root

4,查看kibana运行情况

ps -ef|grep kibana

5,浏览器查看kibana,端口5601

6,至此kibana链接es成功,可以手动写入一个索引,并查看是否写入成功

 6.1 点击kibana中的“工具”,以put形式写入索引book。点击三角按钮,写入成功

6.2 在索引管理中查看刚写入的索引 book,(其它几个索引是logstash启动后写入的日志索引,请继续看下文logstash的安装,启动并写入日志索引)

----------------------------------------------------------- logstash安装 -----------------------------------------------------------

1,安装、启动过程大同小异,不再敖述,主要看配置。

2,单通道配置,也就是读取单个日志文件

input{
    file{
        path => ["/data/elk/logs/debug.log"]
        start_position => "beginning"
    }
}
filter{
    grok{
        match => {"message" => "%{DATA:datetime}\ \[%{DATA:thread}\]\ %{DATA:level} \[%{DATA:class}\]" }
        remove_field => [ "message" ]
    }
    date {
        match => ["datetime","yyyy-MM-dd HH:mm:ss.SSS"]
        
    }
    if "_grokparsefailure" in [tags]{
        drop {}
    }
}
output{
    elasticsearch {      
        hosts => ["192.168.111.111:9200"]
        index => "logger-monitor1-%{+YYYY.MM.dd}"   
    }
}

说明:

        input:是读取logstash所在服务器中文件夹中的日志文件log

        filter:是过滤条件,可以设置读取什么,怎么读

        output:读取到了log并写入到指定ip端口的es中,并命名索引为logger-年月日形式

        这里的Logstash可以是同一个服务器,也可以是另外一台服务器,只要hosts那里改变ip即可,但要注意es所在的服务器要开通防火墙端口访问

3,启动logstash

说明:第一部分是指定全路径下的logstash,第二部分是指logstash是以具体哪个配置启动的(这还只是前台启动,关闭窗口后服务器会停止)

4,启动成功后,可以刷新kibana的页面,查看索引摸索,就看到了写入的索引:

5,如果是有多个日志文件,分部在不同的文件下,那么就采取多通道读取,配置如下:

input{
    file{
        path => ["/home/health/logs/health-monitor-service/debug.log"]
            start_position => "beginning"
            type=> "monitor"
    }
}
input{
    file{
        path => ["/home/health/logs/health-organ-service/debug.log"]
            start_position => "beginning"
            type=> "organ"
    }
}
filter{
    grok{
        match => {"message" => "%{DATA:datetime}\ \[%{DATA:thread}\]\ %{DATA:level} \[%{DATA:class}\]" }
    }
    date {
        match => ["datetime","yyyy-MM-dd HH:mm:ss.SSS"]
        
    }
    if "_grokparsefailure" in [tags]{
        drop {}
    }
}
output{
    if [type]=="monitor" {
            elasticsearch {
                    hosts => ["192.168.111.111:9200"]
                    manage_template => true
                    index => "logger-monitor2-%{+YYYY.MM.dd}"
            }     
     }
    if [type] =="organ" {
            elasticsearch {
                    hosts => ["192.168.111.111:9200"]
                    manage_template => true
                    index => "logger-organ2-%{+YYYY.MM.dd}"
            }     
     }
}

重新启动此配置即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值