关于prometheus:Google-mtail配合Prometheus和Grafana实现自定义日志监控

45次阅读

共计 10446 个字符,预计需要花费 27 分钟才能阅读完成。

前言

mtail 是一个 Google 开发的日志提取工具,相比 ELK/EFK/Grafana Loki 来说会更轻量。因为我遇到的需要只是为了采集生产日志中的数据,所以采纳更为简略的 mtail 配合 Prometheus 和 Grafana 实现自定义日志数据监控。

更新历史

2021 年 08 月 04 日 – 初稿

浏览原文 – https://wsgzao.github.io/post…


常见的日志监控解决方案

开源的业务日志监控,我重点举荐以下 3 个

值得注意的是 ELK 目前有被 EFK 取代的趋势

1:ELK-“ELK”是三个开源我的项目的首字母缩写,这三个我的项目别离是:Elasticsearch、Logstash 和 Kibana。

Elasticsearch 是一个搜寻和剖析引擎。

Logstash 是服务器端数据处理管道,可能同时从多个起源采集数据,转换数据,而后将数据发送到诸如 Elasticsearch 等“存储库”中。

Kibana 则能够让用户在 Elasticsearch 中应用图形和图表对数据进行可视化。

2:Loki,Grafana Labs 团队最新的开源我的项目,是一个程度可扩大,高可用性,多租户的日志聚合零碎。

3:mtail : 它是一个 google 开发的日志提取工具,从应用程序日志中提取指标以导出到工夫序列数据库或工夫序列计算器,

用处就是: 实时读取应用程序的日志、再通过本人编写的脚本进行剖析、最终生成工夫序列指标。

工具适宜本人的才是最好的,无论是 EFK 还是 Loki 都是功能齐全的日志采集零碎,当然它们也有各自的劣势,

Blog 中记录了一些应用教训大家能够参考

Scribe 装置应用 – https://wsgzao.github.io/post…

应用 ELK(Elasticsearch + Logstash + Kibana) 搭建日志集中剖析平台实际 – https://wsgzao.github.io/post…

开源日志治理计划 ELK 和 EFK 的区别 – https://wsgzao.github.io/post…

Grafana Loki 开源日志聚合零碎代替 ELK 或 EFK – https://wsgzao.github.io/post…

mtail 简介

mtail – extract whitebox monitoring data from application logs for collection into a timeseries database

mtail is a tool for extracting metrics from application logs to be exported into a timeseries database or timeseries calculator for alerting and dashboarding.

It fills a monitoring niche by being the glue between applications that do not export their own internal state (other than via logs) and existing monitoring systems, such that system operators do not need to patch those applications to instrument them or writing custom extraction code for every such application.

The extraction is controlled by mtail programs which define patterns and actions:

# simple line counter
counter lines_total
/$/ {lines_total++}

Metrics are exported for scraping by a collector as JSON or Prometheus format over HTTP, or can be periodically sent to a collectd, StatsD, or Graphite collector socket.

mtail 是用于从应用程序日志中提取指标以导出到工夫序列数据库或工夫序列计算器以进行警报和仪表板显示的工具。简略来说,就是实时读取应用程序的日志,并且通过本人编写的脚本实时剖析,最终生成工夫序列指标的工具。

https://github.com/google/mtail

mtail 装置

下载地址:https://github.com/google/mta…

# check latest version from github
wget https://github.com/google/mtail/releases/download/v3.0.0-rc47/mtail_3.0.0-rc47_Linux_x86_64.tar.gz

tar xf mtail_3.0.0-rc47_Linux_x86_64.tar.gz
# can choose to cp mtail to /usr/local/bin
# cp mtail /usr/local/bin

# 查看 mtail 版本
./mtail --version
mtail version 3.0.0-rc47 git revision 5e0099f843e4e4f2b7189c21019de18eb49181bf go version go1.16.5 go arch amd64 go os linux

# mtail 后盾启动
nohup mtail -port 3903 -logtostderr -progs test.mtail -logs test.log &

# 默认端口是 3903
nohup ./mtail -progs test.mtail -logs test.log &

# 查看是否启动胜利
ps -ef | grep mtail

参数详解:控制台运行 mtail -h

上面列举几个简略的参数

参数       形容
-address     绑定 HTTP 监听器的主机或 IP 地址
-alsologtostderr   记录规范谬误和文件
-emit_metric_timestamp   收回 metric 的记录时间戳。如果禁用(默认设置),则不会向收集器发送显式工夫戳。-expired_metrics_gc_interval   metric 的垃圾收集器运行距离(默认为 1h0m0s)-ignore_filename_regex_pattern   须要疏忽的日志文件名字,反对正则表达式。-log_dir   mtail 程序的日志文件的目录,与 logtostderr 作用相似,如果同时配置了 logtostderr 参数,则 log_dir 参数有效
-logs   监控的日志文件列表,能够应用, 分隔多个文件,也能够屡次应用 -logs 参数,也能够指定一个文件目录,反对通配符 *,指定文件目录时须要对目录应用单引号。如:-logs a.log,b.log
      -logs a.log -logs b.log
      -logs‘/export/logs/*.log’-logtostderr   间接输入规范错误信息,编译问题也间接输入
-override_timezone   设置时区,如果应用此参数,将在工夫戳转换中应用指定的时区来代替 UTC
-port   监听的 http 端口,默认 3903
-progs   mtail 脚本程序所在门路
-trace_sample_period   用于设置跟踪的采样频率和发送到收集器的频率。将其设置为 100,则 100 条收集一条追踪。-v   v 日志的日志级别,该设置可能被 vmodule 标记给笼罩. 默认为 0.
-version   打印 mtail 版本

程序启动后默认监听 3903 端口,能够通过 http://ip:3903 拜访,metrics 能够通过 http://ip:3903/metrics 拜访

mtail 参数详解

./mtail -h

mtail version 3.0.0-rc47 git revision 5e0099f843e4e4f2b7189c21019de18eb49181bf go version go1.16.5 go arch amd64 go os linux

Usage:
  -address string
        Host or IP address on which to bind HTTP listener
  -alsologtostderr
        log to standard error as well as files
  -block_profile_rate int
        Nanoseconds of block time before goroutine blocking events reported. 0 turns off.  See https://golang.org/pkg/runtime/#SetBlockProfileRate
  -collectd_prefix string
        Prefix to use for collectd metrics.
  -collectd_socketpath string
        Path to collectd unixsock to write metrics to.
  -compile_only
        Compile programs only, do not load the virtual machine.
  -disable_fsnotify
        DEPRECATED: this flag is no longer in use. (default true)
  -dump_ast
        Dump AST of programs after parse (to INFO log).
  -dump_ast_types
        Dump AST of programs with type annotation after typecheck (to INFO log).
  -dump_bytecode
        Dump bytecode of programs (to INFO log).
  -emit_metric_timestamp
        Emit the recorded timestamp of a metric.  If disabled (the default) no explicit timestamp is sent to a collector.
  -emit_prog_label
        Emit the 'prog' label in variable exports. (default true)
  -expired_metrics_gc_interval duration
        interval between expired metric garbage collection runs (default 1h0m0s)
  -graphite_host_port string
        Host:port to graphite carbon server to write metrics to.
  -graphite_prefix string
        Prefix to use for graphite metrics.
  -ignore_filename_regex_pattern string
    
  -jaeger_endpoint string
        If set, collector endpoint URL of jaeger thrift service
  -log_backtrace_at value
        when logging hits line file:N, emit a stack trace
  -log_dir string
        If non-empty, write log files in this directory
  -logs value
        List of log files to monitor, separated by commas.  This flag may be specified multiple times.
  -logtostderr
        log to standard error instead of files
  -max_recursion_depth int
        The maximum length a mtail statement can be, as measured by parsed tokens. Excessively long mtail expressions are likely to cause compilation and runtime performance problems. (default 100)
  -max_regexp_length int
        The maximum length a mtail regexp expression can have. Excessively long patterns are likely to cause compilation and runtime performance problems. (default 1024)
  -metric_push_interval duration
        interval between metric pushes to passive collectors (default 1m0s)
  -metric_push_interval_seconds int
        DEPRECATED: use --metric_push_interval instead
  -metric_push_write_deadline duration
        Time to wait for a push to succeed before exiting with an error. (default 10s)
  -mtailDebug int
        Set parser debug level.
  -mutex_profile_fraction int
        Fraction of mutex contention events reported.  0 turns off.  See http://golang.org/pkg/runtime/#SetMutexProfileFraction
  -one_shot
        Compile the programs, then read the contents of the provided logs from start until EOF, print the values of the metrics store and exit. This is a debugging flag only, not for production use.
  -override_timezone string
        If set, use the provided timezone in timestamp conversion, instead of UTC.
  -poll_interval duration
        Set the interval to poll all log files for data; must be positive, or zero to disable polling.  With polling mode, only the files found at mtail startup will be polled. (default 250ms)
  -port string
        HTTP port to listen on. (default "3903")
  -progs string
        Name of the directory containing mtail programs
  -stale_log_gc_interval duration
        interval between stale log garbage collection runs (default 1h0m0s)
  -statsd_hostport string
        Host:port to statsd server to write metrics to.
  -statsd_prefix string
        Prefix to use for statsd metrics.
  -stderrthreshold value
        logs at or above this threshold go to stderr
  -syslog_use_current_year
        Patch yearless timestamps with the present year. (default true)
  -trace_sample_period int
        Sample period for traces.  If non-zero, every nth trace will be sampled.
  -unix_socket string
        UNIX Socket to listen on
  -v value
        log level for V logs
  -version
        Print mtail version information.
  -vm_logs_runtime_errors
        Enables logging of runtime errors to the standard log.  Set to false to only have the errors printed to the HTTP console. (default true)
  -vmodule value
        comma-separated list of pattern=N settings for file-filtered logging
参数 形容
-address 绑定 HTTP 监听器的主机或 IP 地址
-alsologtostderr 记录规范谬误和文件
-block\_profile\_rate 报告 goroutine 阻塞事件之前的纳秒工夫
-collectd\_prefix 发送给 collectd 的指标的 metrics 前缀
-collectd\_socketpath collectd unixsock 门路,用于向其写入 metrics
-compile\_only 仅尝试编译 mtail 脚本程序,不执行,用于测试脚本
-disable\_fsnotify 是否禁用文件动静发现机制。为 true 时,不会监听动静加载发现的新文件,只会监听程序启动时的文件。
-dump\_ast 解析后 dump 程序的 AST(默认到 /tmp/mtail.INFO)
-dump\_ast\_types 在类型查看之后 dump 带有类型正文的程序的 AST(默认到 /tmp/mtail.INFO)
-dump\_bytecode dump 程序字节码
-emit\_metric\_timestamp 收回 metric 的记录时间戳。如果禁用(默认设置),则不会向收集器发送显式工夫戳。
-emit\_prog\_label 在导出的变量外面展现’prog’对应的标签。默认为 true
-expired\_metrics\_gc\_interval metric 的垃圾收集器运行距离(默认为 1h0m0s)
-graphite\_host\_port graphite carbon 服务器地址,格局 Host:port。用于向 graphite carbon 服务器写入 metrics
-graphite\_prefix 发送给 graphite 指标的 metrics 前缀
-ignore\_filename\_regex\_pattern 须要疏忽的日志文件名字,反对正则表达式。应用场景:当 -logs 参数指定的为一个目录时,能够应用 ignore\_filename\_regex\_pattern 参数来疏忽一部分文件
-jaeger\_endpoint 如果设为 true,能够将跟踪导出到 Jaeger 跟踪收集器。应用–jaeger\_endpoint 标记指定 Jaeger 端点 URL
-log\_backtrace\_at 当日志记录命中设置的行 N 时,收回堆栈跟踪
-log\_dir mtail 程序的日志文件的目录,与 logtostderr 作用相似,如果同时配置了 logtostderr 参数,则 log\_dir 参数有效
-logs 监控的日志文件列表,能够应用, 分隔多个文件,也能够屡次应用 -logs 参数,也能够指定一个文件目录,反对通配符 *,指定文件目录时须要对目录应用单引号。
-logtostderr 间接输入规范错误信息,编译问题也间接输入
-metric\_push\_interval\_seconds metric 推送工夫距离,单位:秒,默认 60 秒
-metric\_push\_write\_deadline 在呈现谬误退出之前期待推送胜利的工夫。(默认 10s)
-mtailDebug 设置解析器 debug 级别
-mutex\_profile\_fraction 报告的互斥锁争用事件的分数。0 敞开。(此参数为直译,不太了解啥意思)
-one\_shot 此参数将编译并运行 mtail 程序,而后 从指定的文件结尾 开始读取日志(从头开始读取日志,不是实时 tail),而后将收集的所有 metrics 打印到日志中。此参数用于验证 mtail 程序是否有预期输入,不用于生产环境。
-override\_timezone 设置时区,如果应用此参数,将在工夫戳转换中应用指定的时区来代替 UTC
-poll\_interval 设置轮询所有日志文件以获取数据的距离;必须为正,如果为零将禁用轮询。应用轮询模式,将仅轮询在 mtail 启动时找到的文件
-port 监听的 http 端口,默认 3903
-progs mtail 脚本程序所在门路
-stale\_log\_gc\_interval stale 的垃圾收集器运行距离(默认为 1h0m0s)
-statsd\_hostport statsd 地址,格局 Host:port。用于向 statsd 写入 metrics
-statsd\_prefix 发送给 statsd 指标的 metrics 前缀
-stderrthreshold 严重性级别达到阈值以上的日志信息除了写入日志文件以外,还要输入到 stderr。各严重性级别对应的数值:INFO—0,WARNING—1,ERROR—2,FATAL—3,默认值为 2.
-syslog\_use\_current\_year 如果工夫戳没有年份,则用以后年代替。(默认为 true)
-trace\_sample\_period 用于设置跟踪的采样频率和发送到收集器的频率。将其设置为 100,则 100 条收集一条追踪。
-v v 日志的日志级别,该设置可能被 vmodule 标记给笼罩. 默认为 0.
-version 打印 mtail 版本
-vmodule 按文件或模块来设置日志级别,如:-vmodule=mapreduce=2,file=1,gfs*=3

mtail 脚本语法

Read the programming guide if you want to learn how to write mtail programs.

https://github.com/google/mta…

mtail 脚本规范格局

规范格局为:

COND {ACTION}

其中 COND 是一个条件表达式。它能够是正则表达式,也能够 boolean 类型的条件语句。如下:

/foo/ {ACTION1}

variable > 0 {ACTION2}

/foo/ && variable > 0 {ACTION3}

COND表达式可用的运算符如下:

  • 关系运算符:

< , <= , > , >= , == , != , =~ , !~ , || , && , !

  • 算术运算符:

| , & , ^ , + , – , * , /, << , >> , **

导出的指标变量 可用的运算符如下:

\= , += , ++ , –

mtail的目标是从日志中提取信息并将其传递到监控零碎。因而,必须导出指标变量并命名,命名能够应用 counter、、gauge 等指标类型,并且命名的变量必须在 COND 脚本之前。
如,导出一个 counter 类型的指标 lines\_total:统计日志行数,脚本内容如下:

# simple line counter
counter lines_total
/$/ {lines_total++}

mtail 反对的类型

mtail 中的 counter、gauge、histogram 三种类型与 prometheus 类型中形容的作用统一。

counter 类型的数据是枯燥递增的指标,即只增不减。如,你能够应用 counter 类型的指标来示意服务的申请数、胜利工作数、失败的工作数等。

gauge 类型的数据是指能够任意变动的指标,可增可减。如,能够提取正则匹配到的数据,间接赋值给指标变量返回,或者计算后返回。

histogram(直方图)将数据分段统计,援用 prometheus 中对 histogram 的形容:

在大多数状况下人们都偏向于应用某些量化指标的平均值,例如 CPU 的均匀使用率、页面的均匀响应工夫。这种形式的问题很显著,以零碎 API 调用的均匀响应工夫为例:如果大多数 API 申请都维持在 100ms 的响应工夫范畴内,而个别申请的响应工夫须要 5s,那么就会导致某些 WEB 页面的响应工夫落到中位数的状况,而这种景象被称为长尾问题。
为了辨别是均匀的慢还是长尾的慢,最简略的形式就是依照申请提早的范畴进行分组。例如,统计提早在 0~10ms 之间的申请数有多少而 10~20ms 之间的申请数又有多少。通过这种形式能够疾速剖析零碎慢的起因。Histogram 和 Summary 都是为了可能解决这样问题的存在,通过 Histogram 和 Summary 类型的监控指标,咱们能够疾速理解监控样本的散布状况。
Histogram 在一段时间范畴内对数据进行采样(通常是申请持续时间或响应大小等),并将其计入可配置的存储桶(bucket)中,后续可通过指定区间筛选样本,也能够统计样本总数,最初个别将数据展现为直方图。

mtail 详解 – https://blog.csdn.net/bluuuse…

配置 Prometheus 数据源

重启 Prometheus 后,在 Grafana Dashoard 新增一个新的 Panel,再为其配置曾经设置好的 datasource

vim prometheus-config.yml

# 全局配置
global:
  scrape_interval:     15s
  evaluation_interval: 15s

scrape_configs:
  # 监控 mtail 日志
  - job_name: 'mtail'  
    static_configs:
    - targets: ['内网 ip:3903']
    

参考文章

Google mtail

mtail Programming Guide

prometheus+grafana+mtail+node_exporter 实现机器负载及业务监控

mtail 详解

正文完
 0