前言

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 countercounter 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 githubwget https://github.com/google/mtail/releases/download/v3.0.0-rc47/mtail_3.0.0-rc47_Linux_x86_64.tar.gztar 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 --versionmtail 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 &# 默认端口是3903nohup ./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 -hmtail version 3.0.0-rc47 git revision 5e0099f843e4e4f2b7189c21019de18eb49181bf go version go1.16.5 go arch amd64 go os linuxUsage:  -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\_socketpathcollectd unixsock门路,用于向其写入metrics
-compile\_only仅尝试编译mtail脚本程序,不执行,用于测试脚本
-disable\_fsnotify是否禁用文件动静发现机制。为true时,不会监听动静加载发现的新文件,只会监听程序启动时的文件。
-dump\_ast解析后dump程序的AST(默认到/tmp/mtail.INFO)
-dump\_ast\_types在类型查看之后dump带有类型正文的程序的AST(默认到/tmp/mtail.INFO)
-dump\_bytecodedump程序字节码
-emit\_metric\_timestamp收回metric的记录时间戳。如果禁用(默认设置),则不会向收集器发送显式工夫戳。
-emit\_prog\_label在导出的变量外面展现’prog’对应的标签。默认为true
-expired\_metrics\_gc\_intervalmetric的垃圾收集器运行距离(默认为1h0m0s)
-graphite\_host\_portgraphite 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\_dirmtail程序的日志文件的目录,与logtostderr作用相似,如果同时配置了logtostderr参数,则log\_dir参数有效
-logs监控的日志文件列表,能够应用,分隔多个文件,也能够屡次应用-logs参数,也能够指定一个文件目录,反对通配符*,指定文件目录时须要对目录应用单引号。
-logtostderr间接输入规范错误信息,编译问题也间接输入
-metric\_push\_interval\_secondsmetric推送工夫距离,单位:秒,默认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
-progsmtail脚本程序所在门路
-stale\_log\_gc\_intervalstale的垃圾收集器运行距离(默认为1h0m0s)
-statsd\_hostportstatsd地址,格局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条收集一条追踪。
-vv日志的日志级别,该设置可能被 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 countercounter 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: 15sscrape_configs:  # 监控mtail日志  - job_name: 'mtail'      static_configs:    - targets: ['内网ip:3903']    

参考文章

Google mtail

mtail Programming Guide

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

mtail详解