grok_exporter

快速上手grok_exporter

grok_exporter 的核心逻辑和 mtail 一样,就是通过正则从日志中提取指标,我们之前已经介绍过 mtail 的核心逻辑了,所以关于grok_exporter 的介绍会相对简明一些。

grok_exporter 显然是用到了 Grok,Grok 在 logstash 中被重度使用,内置了 100 多个预定义的正则(叫做 pattern),在 grok_exporter 的代码仓库里直接作为 submodule 的方式引用了 logstash-patterns-core,预定义的正则放在了 patterns 目录下,你可以点击查阅。

从 grok_exporter 的 releases 页面下载发布包,解压缩,直接运行就可以。

./grok_exporter -config ./example/config.yml

grok_exporter 默认监听在 9144 端口,我们看下访问测试效果。

[flashcat@fc-demo-02 ~]$ curl -s 10.100.0.7:9144/metrics | head -n 6
# HELP exim_rejected_rcpt_total Total number of rejected recipients, partitioned by error message.
# TYPE exim_rejected_rcpt_total counter
exim_rejected_rcpt_total{error_message="Sender verify failed",logfile="exim-rejected-RCPT-examples.log"} 2000
exim_rejected_rcpt_total{error_message="Unrouteable address",logfile="exim-rejected-RCPT-examples.log"} 32
exim_rejected_rcpt_total{error_message="relay not permitted",logfile="exim-rejected-RCPT-examples.log"} 165
# HELP go_gc_duration_seconds A summary of the pause duration of garbage collection cycles.

通过代码,我们可以看到grok_exporter可以正常拿到监控数据了。下面我们搞一下测试数据,把它放到 example 目录下,保存为 login.log。

12.12.2022 04:33:03 10.1.2.1 user=Ulric message="logged in"
12.12.2022 06:47:03 10.1.2.2 user=Qin message="logged failed"
12.12.2022 06:55:03 10.1.2.2 user=Qin message="logged in"
12.12.2022 07:03:03 10.1.2.3 user=Sofia message="logged in"
12.12.2022 07:37:03 10.1.2.1 user=Ulric message="logged out"
12.12.2022 08:47:03 10.1.2.2 user=Qin message="logged out"
12.12.2022 14:34:03 10.1.2.3 user=Sofia message="logged out"

之后修改 config.yml 来解析login.log。

global:
  config_version: 3
input:
  type: file
  path: ./example/login.log
  readall: true # Read from the beginning of the file? False means we start at the end of the file and read only new lines.
imports:
- type: grok_patterns
  dir: ./patterns
metrics:
- type: counter
  name: user_activity
  help: Counter metric example with labels.
  match: '%{DATE} %{TIME} %{HOSTNAME:instance} user=%{USER:user} message="%{GREEDYDATA:data}"'
  labels:
    user: '{{.user}}'
    logfile: '{{base .logfile}}'
server:
  protocol: http
  port: 9144

使用这个新的配置文件做个测试,下面是返回内容。

[flashcat@fc-demo-02 ~]$ curl -s 10.100.0.7:9144/metrics | grep user_activity
grok_exporter_line_processing_errors_total{metric="user_activity"} 0
grok_exporter_lines_matching_total{metric="user_activity"} 7
grok_exporter_lines_processing_time_microseconds_total{metric="user_activity"} 106
# HELP user_activity Counter metric example with labels.
# TYPE user_activity counter
user_activity{logfile="login.log",user="Qin"} 3
user_activity{logfile="login.log",user="Sofia"} 2
user_activity{logfile="login.log",user="Ulric"} 2

看起来 grok_exporter 要比 mtail 的方式更易用,不过和 mtail 一样,如果要对多个应用程序分别进行日志分析处理,就要启动多个 grok_exporter 实例,这点还是不太方便。当然,在运算方面,grok_exporter 没有 mtail 这种类语言式的处理来得灵活方便。至于选用哪个,尺有所短寸有所长,都学会,具体使用场景具体决策。