写给大忙人的ELK最新版6.2.4学习笔记-Logstash和Filebeat解析(java异常堆栈下多行日志配置支持)
接前一篇CentOS 7下最新版(6.2.4)ELK+Filebeat+Log4j日志集成环境搭建完整指南,继续对ELK。
logstash官方最新文档https://www.elastic.co/guide/en/logstash/current/index.html。
假设有几十台服务器,每台服务器要监控系统日志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。
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 -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: )
--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: )
-u, --pipeline.batch.delay DELAY_IN_MS When creating pipeline batches, how long to wait while polling
for the next event.
(default: )
--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: )
--http.host HTTP_HOST Web API binding host (default: "127.0.0.1")
--http.port HTTP_PORT Web API http port (default: ..)
--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
各配置的含义也可以参考https://www.elastic.co/guide/en/logstash/current/logstash-settings-file.html
比较实用的是:
-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。
Beats Input插件
在开始看具体Input插件之前,我们看下哪些选项是所有插件都支持的。
其中主要的是id,如果一个logstash实例里面开了多个相同类型的插件,可以用来区分。
通过Beats插件加载数据源已经是ELK 6.x的主要推荐方式,所以我们来详细看下Beats插件的配置(https://www.elastic.co/guide/en/logstash/current/plugins-inputs-beats.html)。
input {
beats {
port => 5044
}
}
其中port是参数是必填的,没有默认值。除了ssl配置外,其他几乎都是可选的。
host默认是"0.0.0.0",代表监听所有网卡,除非有特殊安全要求,也是推荐的做法。
核心解析插件Grok Filter
通常来说,各种日志的格式都比较灵活复杂比如nginx访问日志或者并不纯粹是一行一事件比如java异常堆栈,而且还不一定对大部分开发或者运维那么友好,所以如果可以在最终展现前对日志进行解析并归类到各个字段中,可用性会提升很多。grok过滤器插件就是用来完成这个功能的。grok和beat插件一样,默认可用。
从非源头上来说,日志体系好不好,很大程度上依赖于这一步的过滤规则做的好不好,所以虽然繁琐,但却必须掌握,跟nginx的重写差不多。
Logstash自带了约120个模式,具体可见https://github.com/logstash-plugins/logstash-patterns-core/tree/master/patterns。
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的时候详解。
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。
filebeat
从ELK 6.x开始,log4j输入插件已经不再建议使用,推荐的替代是filebat。
filebeat工作原理
参考https://www.elastic.co/guide/en/beats/filebeat/6.2/how-filebeat-works.html
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的命令行选项可以参考https://www.elastic.co/guide/en/beats/filebeat/6.2/command-line-options.html,配置文件所有配置项参考https://www.elastic.co/guide/en/beats/filebeat/6.2/filebeat-reference-yml.html。
默认情况下,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)等
具体可见https://www.elastic.co/guide/en/beats/filebeat/6.2/configuration-filebeat-options.html。
解析多行消息
对于采用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最新版6.2.4学习笔记-Logstash和Filebeat解析(java异常堆栈下多行日志配置支持)的更多相关文章
- ELK学习笔记之Logstash和Filebeat解析对java异常堆栈下多行日志配置支持
0x00 概述 logstash官方最新文档.假设有几十台服务器,每台服务器要监控系统日志syslog.tomcat日志.nginx日志.mysql日志等等,监控OOM.内存低下进程被kill.ngi ...
- 写给大忙人的spring cloud 1.x学习指南
这几天抽空搞了下spring cloud 1.x(2.0目前应该来说还不成熟),因为之前项目中使用dubbo以及自研的rpc框架,所以总体下来还是比较顺利,加上spring boot,不算笔记整理,三 ...
- ELK学习实验017:filebeat收集java日志
收集JAVA格式日志 1 查看Java格式日志 elasticsearch属于Java日志,可以收集elasticsearch作为Java日志范本 [root@node3 ~]# tail -f /u ...
- 写给大忙人的CentOS 7下最新版(6.2.4)ELK+Filebeat+Log4j日志集成环境搭建完整指南
现在的公司由于绝大部分项目都采用分布式架构,很早就采用ELK了,只不过最近因为额外的工作需要,仔细的研究了分布式系统中,怎么样的日志规范和架构才是合理和能够有效提高问题排查效率的.经过仔细的分析和研究 ...
- Egret学习笔记.1 (写在前面的废话)
我记得之前谁说过,大部分程序员入行,都是因为小的时候的游戏机啊,各种电子设备啊....觉得有意思,才入的行 . 至少我本人是因为之前上高中那会儿,喜欢玩手机.那会儿还是MTK,塞班的时代,喜欢拿着手机 ...
- 【linux】【ELK】搭建Elasticsearch+Logstash+Kibana+Filebeat日志收集系统
前言 ELK是Elasticsearch.Logstash.Kibana的简称,这三者是核心套件,但并非全部. Elasticsearch是实时全文搜索和分析引擎,提供搜集.分析.存储数据三大功能:是 ...
- 《写给大忙人看的java se 8》笔记
现在才来了解java8,是不是后知后觉了点? 新的编程技术,个人不喜欢第一时间跟进. 待社区已有实践积淀再切入似乎更划算些? 一点点精明的考虑. 不多说,上代码. //读<写给大忙人看的java ...
- 【读书笔记】《写给大忙人看的Java SE 8》——Java8新特性总结
虽然看过一些Java 8新特性的资料,但是平时很少用到,时间长了就忘了,正好借着Java 9的发布,来总结下一些Java 8中的新特性. 接口中的默认方法和静态方法 先考虑一个问题,如何向Java中的 ...
- 《写给大忙人看的Java核心技术》 勘误
先附上十分讨喜的封面.这应该是爱丽丝梦游仙境里的那只兔子吧? 勘误表基于原版勘误表制作 链接 截止日期 2017-02-09 对应<写给大忙人看的Java核心技术>2016年1月第1次印刷 ...
随机推荐
- 一个toolkit或者一个开源项目如何学习它并使用它
一个toolkit或者一个开源项目如何学习它并使用它 一般一个流行的toolkit和开源项目,一般都会被广泛地被应用: 那么,我们如何学习它,如何应用它在自己的业务场景中呢? 答案就是:学习源码并借鉴 ...
- 使用vscode编译sass
如果你想通过命令行来编译的话 可以按照 https://www.sass.hk/ 前往这里按步骤安装,但是在安装淘宝镜像的时候会有问题,安装不成功,于是我就使用vscode来编译sass 第一步,再v ...
- bat cmd 获取管理员权限
@ echo off % % ver|find "5.">nul&&goto :Admin mshta vbscript:createobject()(win ...
- Sublime text3 经常出现 “ There are no packages avaliable for installation” 解决方法
对应这个问题,一开始在度娘上找到很多答案,包括将json文件放在本地然后通过 package setting 更改的,发现其实不好使,原因未知. 后来测试了在hosts文件添加sublime text ...
- EF或LINQ 查询时使用IN并且根据列表自定义排序方法
EF和LINQ改变了原有的手写SQL时期的一些编码方法,并且增强了各数据库之间的移植性简化了开发时的代码量和难度,由于很多人不熟,经常会碰到一些写SQL语句时经常会用到的一些方法,而使用EF或LINQ ...
- aop编程之后置通知,环绕通知和异常通知
---恢复内容开始--- 此将实例将在上一讲前置通知的基础上进行配置,前置配置内容:http://www.cnblogs.com/lihuibin/p/7955947.html 具体流程如下: 1. ...
- laravel中使用event
https://www.cnblogs.com/ziyouchutuwenwu/p/4274539.html
- C# Control.Invoke匿名委托
if (txbValue.InvokeRequired) txbValue.Invoke(new MethodInvoker(delegate() { ...
- leetcode Sort List 对链表进行排序
描述: Sort a linked list in O(n log n) time using constant space complexity. 在O(n*log(n))的时间复杂度,常数级空间复 ...
- 《大话设计模式》c++实现 外观模式
外观模式:为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用. 外观模式在什么时候使用呢? 分为三个阶段: (1)首先,在设计初期阶段,应该要有意识的 ...