热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

0x00概述logstash官方最新文档。假设有几十台服务器,每台服务器要监控系统日志syslog、tomcat日志、nginx日志、mysql日志等等,监控OOM、内存低下进程被kill

 

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 '>:' 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:>'
    --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以及之后的版本。

 

参考

 


推荐阅读
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • 原文地址:https:www.cnblogs.combaoyipSpringBoot_YML.html1.在springboot中,有两种配置文件,一种 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 本文讨论了在shiro java配置中加入Shiro listener后启动失败的问题。作者引入了一系列jar包,并在web.xml中配置了相关内容,但启动后却无法正常运行。文章提供了具体引入的jar包和web.xml的配置内容,并指出可能的错误原因。该问题可能与jar包版本不兼容、web.xml配置错误等有关。 ... [详细]
  • 如何优化Webpack打包后的代码分割
    本文介绍了如何通过优化Webpack的代码分割来减小打包后的文件大小。主要包括拆分业务逻辑代码和引入第三方包的代码、配置Webpack插件、异步代码的处理、代码分割重命名、配置vendors和cacheGroups等方面的内容。通过合理配置和优化,可以有效减小打包后的文件大小,提高应用的加载速度。 ... [详细]
  • 抽空写了一个ICON图标的转换程序
    抽空写了一个ICON图标的转换程序,支持png\jpe\bmp格式到ico的转换。具体的程序就在下面,如果看的人多,过两天再把思路写一下。 ... [详细]
  • python3 logging
    python3logginghttps:docs.python.org3.5librarylogging.html,先3.5是因为我当前的python版本是3.5之所 ... [详细]
  • 使用 MobX 开发 React Native 应用 @observer 引用报错
    本文将MobX与ReactNative结合,编写一个简单的列表客户端。这是学习使用MobX和ReactNative的一个不错的起点。查看最终的代码库,点 ... [详细]
  • 商品信息|都会_淘淘商城8.6
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了淘淘商城---8.6相关的知识,希望对你有一定的参考价值。继续八月五号写的,今天晚上花点时间开发这个项目& ... [详细]
  • springboot日志【转】【补】
     市面上的日志框架日志门面(日志的抽象层)日志实现JCL(JakartaCommonsLogging)(2014)SLF4j(SimpleLoggingFacadeforJava) ... [详细]
  • javascript  – 概述在Firefox上无法正常工作
    我试图提出一些自定义大纲,以达到一些Web可访问性建议.但我不能用Firefox制作.这就是它在Chrome上的外观:而那个图标实际上是一个锚点.在Firefox上,它只概述了整个 ... [详细]
  • 本文介绍了使用PHP实现断点续传乱序合并文件的方法和源码。由于网络原因,文件需要分割成多个部分发送,因此无法按顺序接收。文章中提供了merge2.php的源码,通过使用shuffle函数打乱文件读取顺序,实现了乱序合并文件的功能。同时,还介绍了filesize、glob、unlink、fopen等相关函数的使用。阅读本文可以了解如何使用PHP实现断点续传乱序合并文件的具体步骤。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 本文详细介绍了Linux中进程控制块PCBtask_struct结构体的结构和作用,包括进程状态、进程号、待处理信号、进程地址空间、调度标志、锁深度、基本时间片、调度策略以及内存管理信息等方面的内容。阅读本文可以更加深入地了解Linux进程管理的原理和机制。 ... [详细]
author-avatar
林小秋
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有