0x00 概述

logstash官方最新文档
假设有几十台服务器,每台服务器要监控系统日志syslog、tomcat日志、nginx日志、mysql日志等等,监控OOM、内存低下进程被kill、nginx错误、mysql异常等等,可想而知,这是多么的耗时耗力。
logstash采用的是插件化体系架构,几乎所有具体功能的实现都是采用插件,已安装的插件列表可以通过bin/logstash-plugin
list
--verbose列出。或者访问https://www.elastic.co/guide/en/logstash/current/input-plugins.html、https://www.elastic.co/guide/en/logstash/current/output-plugins.html。

0x01 logstash配置文件格式

分为输入、过滤器、输出三部分。除了POC目的外,基本上所有实际应用中都需要filter对日志进行预处理,无论是nginx日志还是log4j日志。output中的stdout同理。

input {
log4j {
port => "5400"
}
beats {
port => "5044"
}
}
filter { # 多个过滤器会按声明的先后顺序执行
grok {
match => { "message" => "%{COMBINEDAPACHELOG}"}
}
geoip {
source => "clientip"
}
}
output {
elasticsearch {
action => "index"
hosts => "127.0.0.1:9200" # 或者 ["IP Address 1:port1", "IP Address 2:port2", "IP Address 3"] ,支持均衡的写入ES的多个节点,一般为非master节点
index => "logstash-%{+YYYY-MM}"
}
stdout {
codec=> rubydebug
}
file {
path => "/path/to/target/file"
}
}
# logstash支持的常用输入包括syslog(参考RFC3164)、控制台、文件、redis、beats。
# logstash支持的常用输出包括es、控制台、文件。
# logstash支持的常用过滤器包括grok、mutate、drop、clone、geoip。

查看logstash各种命令行选项

[root@elk1 bin]# ./logstash --help
OpenJDK 64-Bit Server VM warning: If the number of processors is expected to increase from one, then you should configure the number of parallel GC threads appropriately using -XX:ParallelGCThreads=N
Usage:
bin/logstash [OPTIONS] Options:
-n, --node.name NAME Specify the name of this logstash instance, if no value is given
it will default to the current hostname.
(default: "elk1")
-f, --path.config CONFIG_PATH Load the logstash config from a specific file
or directory. If a directory is given, all
files in that directory will be concatenated
in lexicographical order and then parsed as a
single config file. You can also specify
wildcards (globs) and any matched files will
be loaded in the order described above.
-e, --config.string CONFIG_STRING Use the given string as the configuration
data. Same syntax as the config file. If no
input is specified, then the following is
used as the default input:
"input { stdin { type => stdin } }"
and if no output is specified, then the
following is used as the default output:
"output { stdout { codec => rubydebug } }"
If you wish to use both defaults, please use
the empty string for the '-e' flag.
(default: nil)
--modules MODULES Load Logstash modules.
Modules can be defined using multiple instances
'--modules module1 --modules module2',
or comma-separated syntax
'--modules=module1,module2'
Cannot be used in conjunction with '-e' or '-f'
Use of '--modules' will override modules declared
in the 'logstash.yml' file.
-M, --modules.variable MODULES_VARIABLE Load variables for module template.
Multiple instances of '-M' or
'--modules.variable' are supported.
Ignored if '--modules' flag is not used.
Should be in the format of
'-M "MODULE_NAME.var.PLUGIN_TYPE.PLUGIN_NAME.VARIABLE_NAME=VALUE"'
as in
'-M "example.var.filter.mutate.fieldname=fieldvalue"'
--setup Load index template into Elasticsearch, and saved searches,
index-pattern, visualizations, and dashboards into Kibana when
running modules.
(default: false)
--cloud.id CLOUD_ID Sets the elasticsearch and kibana host settings for
module connections in Elastic Cloud.
Your Elastic Cloud User interface or the Cloud support
team should provide this.
Add an optional label prefix '<label>:' to help you
identify multiple cloud.ids.
e.g. 'staging:dXMtZWFzdC0xLmF3cy5mb3VuZC5pbyRub3RhcmVhbCRpZGVudGlmaWVy'
--cloud.auth CLOUD_AUTH Sets the elasticsearch and kibana username and password
for module connections in Elastic Cloud
e.g. 'username:<password>'
--pipeline.id ID Sets the ID of the pipeline.
(default: "main")
-w, --pipeline.workers COUNT Sets the number of pipeline workers to run.
(default: 1)
--experimental-java-execution (Experimental) Use new Java execution engine.
(default: false)
-b, --pipeline.batch.size SIZE Size of batches the pipeline is to work in.
(default: 125)
-u, --pipeline.batch.delay DELAY_IN_MS When creating pipeline batches, how long to wait while polling
for the next event.
(default: 50)
--pipeline.unsafe_shutdown Force logstash to exit during shutdown even
if there are still inflight events in memory.
By default, logstash will refuse to quit until all
received events have been pushed to the outputs.
(default: false)
--path.data PATH This should point to a writable directory. Logstash
will use this directory whenever it needs to store
data. Plugins will also have access to this path.
(default: "/usr/local/app/logstash-6.2.4/data")
-p, --path.plugins PATH A path of where to find plugins. This flag
can be given multiple times to include
multiple paths. Plugins are expected to be
in a specific directory hierarchy:
'PATH/logstash/TYPE/NAME.rb' where TYPE is
'inputs' 'filters', 'outputs' or 'codecs'
and NAME is the name of the plugin.
(default: [])
-l, --path.logs PATH Write logstash internal logs to the given
file. Without this flag, logstash will emit
logs to standard output.
(default: "/usr/local/app/logstash-6.2.4/logs")
--log.level LEVEL Set the log level for logstash. Possible values are:
- fatal
- error
- warn
- info
- debug
- trace
(default: "info")
--config.debug Print the compiled config ruby code out as a debug log (you must also have --log.level=debug enabled).
WARNING: This will include any 'password' options passed to plugin configs as plaintext, and may result
in plaintext passwords appearing in your logs!
(default: false)
-i, --interactive SHELL Drop to shell instead of running as normal.
Valid shells are "irb" and "pry"
-V, --version Emit the version of logstash and its friends,
then exit.
-t, --config.test_and_exit Check configuration for valid syntax and then exit.
(default: false)
-r, --config.reload.automatic Monitor configuration changes and reload
whenever it is changed.
NOTE: use SIGHUP to manually reload the config
(default: false)
--config.reload.interval RELOAD_INTERVAL How frequently to poll the configuration location
for changes, in seconds.
(default: 3000000000)
--http.host HTTP_HOST Web API binding host (default: "127.0.0.1")
--http.port HTTP_PORT Web API http port (default: 9600..9700)
--log.format FORMAT Specify if Logstash should write its own logs in JSON form (one
event per line) or in plain text (using Ruby's Object#inspect)
(default: "plain")
--path.settings SETTINGS_DIR Directory containing logstash.yml file. This can also be
set through the LS_SETTINGS_DIR environment variable.
(default: "/usr/local/app/logstash-6.2.4/config")
--verbose Set the log level to info.
DEPRECATED: use --log.level=info instead.
--debug Set the log level to debug.
DEPRECATED: use --log.level=debug instead.
--quiet Set the log level to info.
DEPRECATED: use --log.level=quiet instead.
-h, --help print help

各配置的含义也可以参考
比较实用的是:

# -f filename.conf 指定配置文件
# --config.test_and_exit 解析配置文件正确性
# --config.reload.automatic 自动监听配置修改而无需重启,跟nginx -s reload一样,挺实用的

ELK均采用YAML语言(https://baike.baidu.com/item/YAML/1067697?fr=aladdin)编写配置文件。

YAML有以下基本规则:

# 1、大小写敏感
# 2、使用缩进表示层级关系
# 3、禁止使用tab缩进,只能使用空格键
# 4、缩进长度没有限制,只要元素对齐就表示这些元素属于一个层级。
# 5、使用#表示注释
# 6、字符串可以不用引号标注

JVM参数在config/jvm.options中设置。

# 配置文件中output和filter部分均支持主要常见的逻辑表达式比如if/else if,以及各种比较、正则匹配。
# 配置文件中还可以访问环境变量,通过${HOME}即可,具体可以参考https://www.elastic.co/guide/en/logstash/current/environment-variables.html。

0x02 Beats Input插件

在开始看具体Input插件之前,我们看下哪些选项是所有插件都支持的。
其中主要的是id,如果一个logstash实例里面开了多个相同类型的插件,可以用来区分。

通过Beats插件加载数据源已经是ELK 6.x的主要推荐方式,所以我们来详细看下Beats插件的配置

input {
beats {
port => 5044
}
}

其中port是参数是必填的,没有默认值。除了ssl配置外,其他几乎都是可选的。
host默认是"0.0.0.0",代表监听所有网卡,除非有特殊安全要求,也是推荐的做法。

0x03 核心解析插件Grok Filter

通常来说,各种日志的格式都比较灵活复杂比如nginx访问日志或者并不纯粹是一行一事件比如java异常堆栈,而且还不一定对大部分开发或者运维那么友好,所以如果可以在最终展现前对日志进行解析并归类到各个字段中,可用性会提升很多。

grok过滤器插件就是用来完成这个功能的。grok和beat插件一样,默认可用。
从非源头上来说,日志体系好不好,很大程度上依赖于这一步的过滤规则做的好不好,所以虽然繁琐,但却必须掌握,跟nginx的重写差不多。

# Logstash自带了约120个模式,具体可见。
# grok的语法为:%{SYNTAX:SEMANTIC}

类似于java:

String pattern = ".*runoob.*";
boolean isMatch = Pattern.matches(pattern, content);

其中的pattern就相当于SYNTAX,SEMANTIC为content,只不过因为解析的时候没有字段名,所以content是赋给匹配正则模式的文本的字段名,这些字段名会被追加到event中。

例如对于下列http请求日志:

55.3.244.1 GET /index.html 15824 0.043
# 使用 %{IP:client} %{WORD:method} %{URIPATHPARAM:request} %{NUMBER:bytes} %{NUMBER:duration} 匹配的话,除了原message外,事件中会新增下列额外字段:
client: 55.3.244.1
method: GET
request: /index.html
bytes: 15824
duration: 0.043

完整的grok例子如下:

input {
file {
path => "/var/log/http.log"
}
}
filter {
grok {
match => { "message" => "%{IP:client} %{WORD:method} %{URIPATHPARAM:request} %{NUMBER:bytes} %{NUMBER:duration}" }
}
}

注:如果重启,logstash怎么知道读取到http.log的什么位置了,在filebeat部分,我们会讲到。
grok的主要选项是match和overwrite,前者用来解析message到相应字段,后者用来重写message,这样原始message就可以被覆盖,对于很多的日志来说,原始的message重复存储一份没有意义。

https://www.elastic.co/guide/en/logstash/6.2/plugins-filters-grok.html#plugins-filters-grok-overwrite

虽然Grok过滤器可以用来进行格式化,但是对于多行事件来说,并不适合在filter或者input(multiline
codec,如果希望在logstash中处理多行事件,可以参考https://www.elastic.co/guide/en/logstash/current/multiline.html)中处理,因为使用ELK的平台通常日志使用beats

input插件,此时在logstash中进行多行事件的处理会导致数据流混乱,所以需要在事件发送到logstash之前就处理好,也就是应该在filebeat中预处理。

对于来自于filebeat模块的数据,logstash自带了针对他们的解析模式,参考https://www.elastic.co/guide/en/logstash/current/logstash-config-for-filebeat-modules.html,具体到filebeat的时候详解。

0x04 ES Output插件

主要的选项包括:

# action,默认是index,索引文档(logstash的事件)(ES架构与核心概念参考)。
# host,声明ES服务器地址端口
# index,事件写入的ES index,默认是logstash-%{+YYYY.MM.dd},按天分片index,一般来说我们会按照时间分片,时间格式参考http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html。

1. filebeat

从ELK 6.x开始,log4j输入插件已经不再建议使用,推荐的替代是filebat。

2. filebeat工作原理

参考

Filebeat由两个主要组件组成,

prospectors和harvesters,他们一起协作tail文件并将事件发送给声明的输出。

harvester的职责是以行为单位读取文件,发送给输出,每个文件由不同的harvester读取。

prospector的职责是管理harvester并找到要读取的文件。

Filebeat当前支持log和stdin这两种prospector,每种prospector可以定义多次。

Filebeat在注册表(通过参数filebeat.registry_file声明,默认是${path.data}/registry)中记录了每个文件的状态,状态记录了上一次harvester的读取偏移量。prospector则记录了每个找到的文件的状态。Filebeat确保所有的事件都被发送至少一次。

filebeat的配置文件同样采用YAML格式。

filebeat.prospectors:
- type: log
paths:
- /var/log/*.log # 声明日志文件的绝对路径
fields:
type: syslog # 声明增加一个值为syslog的type字段到事件中
output.logstash:
hosts: ["localhost:5044"]

filebeat支持输出到Elasticsearch或者Logstash,一般来说通行的做法都是到Logstash,所以到ES的相关配置略过。
filebeat的命令行选项可以参考,配置文件所有配置项参考

默认情况下,filebeat运行在后台,要以前台方式启动,运行./filebeat -e。

要使用Filebeat,我们需要在filebeat.yml配置文件的filebeat.prospectors下声明prospector,prospector不限定只有一个。例如:

filebeat.prospectors:
- type: log
paths:
- /var/log/apache/httpd-*.log - type: log
paths:
- /var/log/messages
- /var/log/*.log

其他有用的选项还包括include_lines(仅读取匹配的行)、exclude_lines(不读取匹配的行)、exclude_files(排除某些文件)、tags、fields、fields_under_root、close_inactive(日志文件多久没有变化后自动关闭harvester,默认5分钟)、scan_frequency(prospector为harvester扫描新文件的频率,注意,因close_inactive自动关闭的也算新文件,默认为10s,不要低于1s)等
具体可见

3. 解析多行消息

对于采用ELK作为应用日志来说,多行消息的友好展示是必不可少的,否则ELK的价值就大大打折了。要正确的处理多行消息,需要在filebeat.yml中设置multiline规则以声明哪些行属于一个事件。主要是由multiline.pattern、multiline.negate、multiline.match这三个参数决定。
比如,对于java日志而言,可以使用:

multiline.pattern: '^\['
multiline.negate: true
multiline.match: after

或者:

multiline.pattern: '^[[:space:]]+(at|\.{3})\b|^Caused by:'
multiline.negate: false
multiline.match: after

这样,下面的日志就算一个事件了。

beat-logstash-some-name-832-2015.11.28] IndexNotFoundException[no such index]
at org.elasticsearch.cluster.metadata.IndexNameExpressionResolver$WildcardExpressionResolver.resolve(IndexNameExpressionResolver.java:566)
at org.elasticsearch.cluster.metadata.IndexNameExpressionResolver.concreteIndices(IndexNameExpressionResolver.java:133)
at org.elasticsearch.cluster.metadata.IndexNameExpressionResolver.concreteIndices(IndexNameExpressionResolver.java:77)
at org.elasticsearch.action.admin.indices.delete.TransportDeleteIndexAction.checkBlock(TransportDeleteIndexAction.java:75)

详细的配置可以参考https://www.elastic.co/guide/en/beats/filebeat/6.2/multiline-examples.html。

Filebeat支持的输出包括Elasticsearch、Logstash、Kafka、Redis、File、Console,都挺简单,可以参考https://www.elastic.co/guide/en/beats/filebeat/6.2/kafka-output.html。

Filebeat模块提供了一种更便捷的方式处理常见的日志格式,比如apache2、mysql等。从性质上来说,他就像spring boot,约定优于配置。具体可以参考https://www.elastic.co/guide/en/beats/filebeat/6.2/filebeat-modules-overview.html。Filebeat模块要求Elasticsearch 5.2以及之后的版本。

参考

ELK学习笔记之Logstash和Filebeat解析对java异常堆栈下多行日志配置支持的更多相关文章

  1. 写给大忙人的ELK最新版6.2.4学习笔记-Logstash和Filebeat解析(java异常堆栈下多行日志配置支持)

    接前一篇CentOS 7下最新版(6.2.4)ELK+Filebeat+Log4j日志集成环境搭建完整指南,继续对ELK. logstash官方最新文档https://www.elastic.co/g ...

  2. ELK学习笔记之Logstash详解

    0x00 Logstash概述 官方介绍:Logstash is an open source data collection engine with real-time pipelining cap ...

  3. ELK学习笔记之logstash安装logstash-filter-multiline(在线离线安装)

    0x00 概述 ELK-logstash在搬运日志的时候会出现多行日志,普通的搬运会造成保存到ES中单条单条,很丑,而且不方便读取,logstash-filter-multiline可以解决该问题 g ...

  4. ELK学习笔记之logstash将配置写在多个文件

    0x00 概述 我们用Logsatsh写配置文件的时候,如果读取的文件太多,匹配的正则过多,会使配置文件动辄成百上千行代码,可能会造成阅读和修改困难.这时候,我们可以将配置文件的输入.过滤.输出分别放 ...

  5. ELK 学习笔记之 Logstash之output配置

    Logstash之output配置: 输出到file 配置conf: input{ file{ path => "/usr/local/logstash-5.6.1/bin/spark ...

  6. ELK 学习笔记之 Logstash之filter配置

    Logstash之filter: json filter: input{ stdin{ } } filter{ json{ source => "message" } } o ...

  7. ELK 学习笔记之 Logstash之codec配置

    Logstash之codec: Logstash处理流程: input=>decode=>filter=>encode=>output 分类: Plain编码: input{ ...

  8. ELK 学习笔记之 Logstash之inputs配置

    Logstash之inputs配置: input plugin doc: https://www.elastic.co/guide/en/logstash/current/index.html 插件很 ...

  9. ELK 学习笔记之 Logstash基本语法

    Logstash基本语法: 处理输入的input 处理过滤的filter 处理输出的output 区域 数据类型 条件判断 字段引用 区域: Logstash中,是用{}来定义区域 区域内,可以定义插 ...

随机推荐

  1. <input type=file>上传唯一控件

    值得注意的是:当一个表单里面包含这个上传元素的时候,表单的enctype必须指定为multipart/form-data,method必须指定为post,浏览器才会认识并正确执行.但是还有一点,浏览器 ...

  2. 新建虚拟机_XP系统(一)

    准备工作:(1)安装VMware (2)下载系统镜像文件 1.新建虚拟机 2.下一步,选择“稍后安装操作系统” 3.选择操作系统类型和版本 4.设置虚拟机名称和安装位置 (安装路径空间要足够大) 5. ...

  3. 基础邮件原理(MUA,MTA,MDA)

    电子邮件基本概念: MUA(Mail User Agent)接收邮件所使用的邮件客户端,使用IMAP或POP3协议与服务器通信: MTA(Mail Transfer Agent) 通过SMTP协议发送 ...

  4. CentOS 7显卡驱动问题

    CentOS 7 KDE桌面安装后有时会出现nouveau 驱动问题,导致系统不定时死机或者重启,那么这时只能禁用nouveau 1. 在配置文件中禁用nouveauvi /etc/modprobe. ...

  5. kubernetes实战(十二):k8s使用helm持久化部署redmine集成openLDAP

    1.基本概念 此次安装的有Jenkins.Gitlab.Redmine,我公司目前使用的是独立于k8s集群之外单独部署的Jenkins等服务,此文章会介绍三种服务基于k8s的部署方式,之后集成之前部署 ...

  6. Service 的 onStartCommand(Intent, int, int) 返回值

    (1)START_NOT_STICKY If the system kills the service after onStartCommand() returns, do not recreate ...

  7. Loadrunner之脚本的思考时间(固定/随机)设置、调试、保存、测试服务器监控等(六)

    一.思考时间的设置 1)设置固定思考时间: Action(){ // … your code lr_think_time(3); //固定设置此处思考时间3s // … more of your co ...

  8. Jedis 对 Redis 的操作详解

    1. JedisUtil2. 键操作3. 字符串操作4. 字节串4. 整数和浮点数5. 列表6. 集合(Set)7. 散列8. 排序sort 本篇主要阐述Jedis对redis的五大类型的操作:字符串 ...

  9. java-信息安全(十一)-非对称加密算法ECC以及ECDSA签名

    概述 信息安全基本概念: ECC算法(Elliptic curve cryptography,椭圆曲线密码学) 一.ECC加密解密[暂时无意义] 椭圆加密算法(ECC)是一种公钥加密体制,最初由Kob ...

  10. 如何调用另一个python文件中的代码

    模块的搜索路径 模块的搜索路径都放在了sys.path列表中,如果缺省的sys.path中没有含有自己的模块或包的路径,可以动态的加入(sys.path.apend)即可.下面是sys.path在Wi ...