Telegraf MongoDB 输入插件实战指南:采集、指标解析与监控配置全解
2026/9/14 17:17:30 网站建设 项目流程

Telegraf MongoDB 输入插件实战指南:采集、指标解析与监控配置全解

【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegraf

Telegraf 官方 MongoDB 输入插件通过执行 MongoDB 数据库命令,从单个或多个 MongoDB 服务端实例采集服务器状态、副本集、分片集群、数据库、集合等多维度指标。本文围绕 plugins/inputs/mongodb/README.md 展开,完整讲解插件配置参数、权限要求、五类监控指标(mongodb / mongodb_db_stats / mongodb_col_stats / mongodb_shard_stats / mongodb_top_stats)的含义与来源,并结合仓库源码(mongodb.go、mongodb_server.go、mongodb_data.go)剖析底层采集流程,帮助你快速落地 MongoDB 的可观测性方案。

插件概述

该插件以inputs.mongodb为插件名注册到 Telegraf 输入插件体系中(见 mongodb.go 中的inputs.Add("mongodb", ...)),是 Telegraf 最早的输入插件之一(v0.1.5 起即存在)。它通过 MongoDB 官方 Go Driver 连接服务端,并运行一系列数据库命令来获取实时状态。

插件支持 MongoDB 软件生命周期计划中标记为受支持的所有版本(MongoDB Software Lifecycle Schedules)。在数据采集上,它借鉴了官方mongostat工具的统计模型:对两次采样之间的计数型指标做差值计算,从而得到"每秒速率"与累计值两类字段。

配置文件与核心参数

插件的标准配置模板定义在 sample.conf.in(其中 TLS 部分通过模板引入 plugins/common/tls/client.conf),生成后的完整示例见 sample.conf。以下是完整可用的配置块:

# Read metrics from one or many MongoDB servers [[inputs.mongodb]] ## An array of URLs of the form: ## "mongodb://" [user ":" pass "@"] host [ ":" port] ## For example: ## mongodb://user:auth_key@10.10.3.30:27017, ## mongodb://10.10.3.33:18832, ## ## If connecting to a cluster, users must include the "?connect=direct" in ## the URL to ensure that the connection goes directly to the specified node ## and not have all connections passed to the master node. servers = ["mongodb://127.0.0.1:27017/?connect=direct"] ## When true, collect cluster status. ## Note that the query that counts jumbo chunks triggers a COLLSCAN, which ## may have an impact on performance. # gather_cluster_status = true ## When true, collect per database stats # gather_perdb_stats = false ## When true, collect per collection stats # gather_col_stats = false ## When true, collect usage statistics for each collection ## (insert, update, queries, remove, getmore, commands etc...). # gather_top_stat = false ## List of db where collections stats are collected ## If empty, all db are concerned # col_stats_dbs = ["local"] ## Optional TLS Config ## Set to true/false to enforce TLS being enabled/disabled. If not set, ## enable TLS only if any of the other options are specified. # tls_enable = ## Trusted root certificates for server # tls_ca = "/path/to/cafile" ## Used for TLS client certificate authentication # tls_cert = "/path/to/certfile" ## Used for TLS client certificate authentication # tls_key = "/path/to/keyfile" ## Password for the key file if it is encrypted # tls_key_pwd = "" ## Send the specified TLS server name via SNI # tls_server_name = "kubernetes.example.com" ## Minimal TLS version to accept by the client # tls_min_version = "TLS12" ## List of ciphers to accept, by default all secure ciphers will be accepted ## See https://pkg.go.dev/crypto/tls#pkg-constants for supported values. ## Use "all", "secure" and "insecure" to add all support ciphers, secure ## suites or insecure suites respectively. # tls_cipher_suites = ["secure"] ## Renegotiation method, "never", "once" or "freely" # tls_renegotiation_method = "never" ## Use TLS but skip chain & host verification # insecure_skip_verify = false ## Specifies plugin behavior regarding disconnected servers ## Available choices : ## - error: telegraf will return an error on startup if one the servers is unreachable ## - skip: telegraf will skip unreachable servers on both startup and gather # disconnected_servers_behavior = "error"

servers:连接地址数组

servers接受一组 MongoDB 连接 URL,格式为"mongodb://" [user ":" pass "@"] host [ ":" port],例如:

  • mongodb://user:auth_key@10.10.3.30:27017(带认证)
  • mongodb://10.10.3.33:18832(自定义端口)
  • mongodb://127.0.0.1:27017/?connect=direct(默认值)

连接集群时必须在 URL 中携带?connect=direct,确保连接直达指定节点,避免所有连接都被转发到主节点(master node),这对分片集群与副本集的多节点采集至关重要。插件在 mongodb.go 的setupConnection中会对未带 scheme 的主机名做向后兼容处理:若 URL 不以mongodb://mongodb+srv://开头,会自动补全mongodb://前缀并输出警告日志,建议用户尽快改用完整的 URL 写法。

servers未配置,插件默认使用mongodb://127.0.0.1:27017(见 mongodb.go)。连接建立时还会设置默认读偏好为readpref.Nearest()(就近读取),见 mongodb.go。

采集开关:四类可选统计

配置项默认值作用实现命令
gather_cluster_statustrue采集集群状态(jumbo chunks 数量)config.chunks集合执行countDocuments({"jumbo": true})
gather_perdb_statsfalse逐数据库采集统计(mongodb_db_stats)dbStats命令
gather_col_statsfalse逐集合采集统计(mongodb_col_stats)collStats命令
gather_top_statfalse采集每个集合的读写锁耗时等使用统计(mongodb_top_stats)top命令

四个开关在 mongodb.go 中对应GatherClusterStatusGatherPerDBStatsGatherColStatsGatherTopStat四个结构体字段。

需要特别注意两点:

  1. gather_cluster_status统计 jumbo chunks 的查询会触发COLLSCAN(全集合扫描),在数据量大的分片集群上可能带来性能影响,默认虽然开启,但生产环境需评估是否保留。
  2. gather_perdb_statsgather_col_stats默认关闭,因为它们需要对每个数据库/集合逐个执行命令,数据库与集合数量较多时采集开销会明显上升。

col_stats_dbs:集合统计的数据库白名单

gather_col_stats = true时,用col_stats_dbs限定统计哪些数据库下的集合。若列表为空,则统计所有数据库;默认值为["local"]。在 mongodb_server.go 的gatherCollectionStats中,插件先列出所有数据库名,再对命中的数据库过滤出typecollectiontimeseries的集合(跳过视图,因为视图执行collStats会失败),最后逐集合运行collStats命令。

TLS 配置

插件内嵌了 Telegraf 通用的 TLS 客户端配置(common_tls.ClientConfig,见 mongodb.go),在Init阶段通过ClientConfig.TLSConfig()生成*tls.Config并挂到每个连接上(mongodb.go、mongodb.go)。关键项包括:

  • tls_enable:显式强制启用/禁用 TLS;未设置时仅当其他 TLS 选项被指定才启用。
  • tls_ca/tls_cert/tls_key/tls_key_pwd:CA 根证书、客户端证书、私钥及其加密密码。
  • tls_server_name:通过 SNI 发送的服务器名。
  • tls_min_version:客户端接受的最低 TLS 版本,默认TLS12
  • tls_cipher_suites:接受的密码套件列表,可取值"all""secure""insecure"或具体套件名,默认["secure"]
  • tls_renegotiation_method:重协商方式,"never""once""freely"
  • insecure_skip_verify:跳过证书链与主机名校验(仅测试环境使用)。

disconnected_servers_behavior:断连服务器行为

该参数决定服务器不可达时的插件行为(mongodb.go):

  • error(默认):任一台服务器启动时不可达,Telegraf 直接返回启动错误。
  • skip:启动与每次采集时跳过不可达的服务器,并在 Gather 阶段先ping探测,失败则只记录 debug 日志、跳过该节点采集(mongodb.go)。

此行为在 mongodb_server_test.go 中有集成测试验证:skip模式下即使连接地址不可达,InitStartGather也不会报错。

全局配置选项

与所有 Telegraf 插件一样,inputs.mongodb支持通用的全局与插件级配置,例如使用namepassfieldpasstagexclude等对指标、标签、字段进行过滤与重命名,或配置插件别名与执行顺序,详见 docs/CONFIGURATION.md。

权限要求与常见错误

如果 MongoDB 实例开启了访问控制,需要以具备足够权限的用户连接。

  • MongoDB 3.4 及以上版本:使用clusterMonitor角色即可覆盖本插件所需的serverStatusreplSetGetStatusdbStatscollStatstopconnPoolStats等命令权限。
  • MongoDB 3.2 及更早版本:可能还需要额外授予对local库的find权限:
> db.grantRolesToUser("user", [{role: "read", actions: "find", db: "local"}])

当用户缺少必要权限时,Telegraf 日志中会出现类似错误:

Error in input [mongodb]: not authorized on admin to execute command { serverStatus: 1, recordStats: 0 }

从源码看,插件对权限类错误做了专门处理:mongodb_server.go 中的isAuthorization判断错误信息是否包含"not authorized",若属于权限问题则降级为 debug 级别日志,其他错误才以 error 级别输出(见authLog函数,mongodb_server.go)。因此排查权限问题时,建议开启 debug 日志:

  • 在配置的[agent]段设置debug = true,或
  • 运行 Telegraf 时加--debug参数。

采集原理:基于数据库命令的两次采样差分

插件的工作流清晰体现在 mongodb.go 的生命周期方法中:

  1. Init:校验disconnected_servers_behavior、构建 TLS 配置、补齐默认 servers。
  2. Start:逐个 URL 调用setupConnection建立 MongoDB 连接(mongo.ConnectPing探测)。
  3. Gather:并发(goroutine + WaitGroup)对每个已连接服务器执行gatherData
  4. Stop:带 10 秒超时断开所有连接,用于插件重载/停止场景。

gatherData(mongodb_server.go)是核心采集函数,顺序执行以下命令并组装为一次采样快照(mongoStatus):

数据来源执行的命令/查询说明
serverStatus{serverStatus: 1, recordStats: 0}服务器整体状态(连接、内存、网络、WiredTiger、TCMalloc 等)
replSetGetStatus{replSetGetStatus: 1}副本集成员状态;失败说明非副本集成员,仅记 debug 日志
oplog 延迟查询local.oplog.rs(或已弃用的oplog.$main)首尾记录计算复制延迟repl_lag与 oplog 时间窗口repl_oplog_window_sec
集群状态config.chunks集合countDocuments({"jumbo": true})统计 jumbo chunks 数
分片连接池shardConnPoolStats(MongoDB < 5.0)/connPoolStats(≥ 5.0)按版本选择命令,见 mongodb_server.go
数据库统计逐库执行dbStatsgather_perdb_stats控制
集合统计逐集合执行collStatsgather_col_statscol_stats_dbs控制
集合使用统计top命令gather_top_stat控制

关键设计:插件保留上一次采样的lastResult,只有连续两次采样后才能产出指标。在 mongodb_server.go 中,插件计算两次采样时间差(不足 1 秒按 1 秒计),调用newStatLine(源自官方 mongostat 的统计模型,见 mongostat.go 头部注释)对计数型字段做差分,从而同时输出累计值与每秒速率两类字段。这也意味着 Telegraf 启动后的第一次采集通常不产生 mongodb 指标,第二次采集才开始输出——mongodb_server_test.go 的集成测试正是连续调用两次gatherData以完成差分后校验字段。

指标字段映射集中在 mongodb_data.go 的多个映射表中:defaultStats(opcounters、游标、文档、连接等)、defaultReplStats(副本集)、defaultClusterStatsdefaultCommandsStatsdefaultLatencyStatsdefaultTCMallocStatsdefaultStorageStats以及 WiredTiger 相关的wiredTigerStats/wiredTigerExtStats/wiredTigerConnectionStats/wiredTigerDataHandleStats。存储引擎相关字段(如percent_cache_dirtypercent_cache_usedwtcache_*)仅在存储引擎为wiredTiger时输出,MMAPv1 引擎则输出mapped_megabytespage_faults等字段(mongodb_data.go)。

指标详解:五类测量(Measurement)

mongodb:服务器整体状态

  • tags:hostnamenode_typers_name
    • hostname恒存在,来自连接 URL 的主机:端口。
    • node_type(如PRI/SEC)与rs_name(副本集名称)仅在服务器属于副本集时添加,见 mongodb_data.go。
  • fields(节选核心项):
    • 连接connections_currentconnections_availableconnections_total_createdopen_connections
    • 操作计数insertsqueriesupdatesdeletesgetmorescommandsflushes(后接_per_sec后缀的为速率字段,如inserts_per_sec
    • 命令成功/失败aggregate_command_total/aggregate_command_failedfind_command_total/find_command_failedinsert_command_total/insert_command_failedupdate_command_total/update_command_faileddelete_command_total/delete_command_failedcount_command_total/count_command_faileddistinct_command_total/distinct_command_failedfind_and_modify_command_total/find_and_modify_command_failedget_more_command_total/get_more_command_failed
    • 延迟latency_reads/latency_reads_countlatency_writes/latency_writes_countlatency_commands/latency_commands_count(读、写、命令总延迟及操作数,可求平均值)
    • 内存与缓存resident_megabytesvsize_megabytespercent_cache_dirtypercent_cache_usedpage_faults
    • 游标cursor_total/cursor_total_countcursor_timed_out/cursor_timed_out_countcursor_no_timeout/cursor_no_timeout_countcursor_pinned/cursor_pinned_count
    • TTLttl_passes/ttl_passes_per_secttl_deletes/ttl_deletes_per_sec
    • 文档操作document_inserteddocument_updateddocument_deleteddocument_returned
    • 锁与并发active_readsactive_writesqueued_readsqueued_writesavailable_readsavailable_writestotal_tickets_readstotal_tickets_writes
    • 副本集member_statusstate(如PRIMARY)、repl_staterepl_member_healthrepl_health_avgrepl_lagrepl_oplog_window_sec以及repl_apply_*repl_buffer_*repl_executor_*repl_network_*
    • 存储storage_freelist_search_bucket_exhaustedstorage_freelist_search_requestsstorage_freelist_search_scanned
    • WiredTigerwtcache_*系列(缓存字节、页读入/写出、逐出统计等)、wt_connection_files_currently_openwt_data_handles_currently_active
    • TCMalloctcmalloc_*系列(堆大小、pageheap 提交/释放/保留统计等)
    • 其他assert_msgassert_regularassert_rolloversassert_userassert_warningflushes_total_time_nsjumbo_chunksoperation_scan_and_orderoperation_write_conflictstotal_docs_scannedtotal_keys_scanneduptime_nsversionnet_in_bytes_countnet_out_bytes_count

1.10 版本的字段弃用说明:一批_per_sec速率字段与部分累计字段自 Telegraf 1.10 起被弃用,需改用对应的_count累计字段,例如commands_per_seccommandscursor_totalcursor_total_countnet_in_bytesnet_in_bytes_countrepl_inserts_per_secrepl_inserts。完整对应关系见 README 的 Metrics 列表,新配置应直接使用新版字段。

mongodb_db_stats:按数据库统计

  • tags:db_namehostname
  • fields:avg_obj_sizecollectionsdata_sizeindex_sizeindexesnum_extentsobjectsokstorage_sizetype(固定为"db_stat")、fs_used_sizefs_total_size

dbStats命令驱动,每个数据库输出一条记录,适合观察各库的数据量与对象数增长。

mongodb_col_stats:按集合统计

  • tags:hostnamecollectiondb_name
  • fields:sizeavg_obj_sizestorage_sizetotal_index_sizeokcounttype(固定为"col_stat"

collStats命令驱动,受gather_col_statscol_stats_dbs控制。可用于定位大集合、大索引与文档数增长。

mongodb_shard_stats:分片连接池统计

  • tags:hostname
  • fields:in_useavailablecreatedrefreshing

shardConnPoolStats(MongoDB < 5.0)或connPoolStats(≥ 5.0)命令驱动,按分片主机输出连接池使用情况,用于评估分片集群的连接饱和度。

mongodb_top_stats:集合使用统计

  • tags:collection
  • fields:total_timetotal_countread_lock_timeread_lock_countwrite_lock_timewrite_lock_countqueries_timequeries_countget_more_timeget_more_countinsert_timeinsert_countupdate_timeupdate_countremove_timeremove_countcommands_timecommands_count

top命令驱动,记录每个集合在读锁、写锁、查询、getmore、插入、更新、删除、命令等操作上花费的时间与次数,用于定位热点集合。注意该命令在 mongodb_server.go 中的实现会先以map[string]interface{}接收原始返回,剔除note键后再反序列化为结构化数据。

输出示例

以下为 README 中的真实输出样例(influx line protocol,节选),展示了单机(无副本集)与副本集节点两类mongodb指标,以及mongodb_db_statsmongodb_col_statsmongodb_shard_statsmongodb_top_stats的典型形态:

mongodb,hostname=127.0.0.1:27017 active_reads=1i,active_writes=0i,assert_msg=0i,assert_regular=0i,assert_user=0i,available_reads=127i,available_writes=128i,commands=65i,connections_available=51199i,connections_current=1i,connections_total_created=5i,flushes=52i,flushes_total_time_ns=364000000i,inserts=0i,jumbo_chunks=0i,latency_commands=5740i,latency_reads=348i,open_connections=1i,page_faults=1i,percent_cache_dirty=0,percent_cache_used=0,queries=1i,queued_reads=0i,queued_writes=0i,resident_megabytes=33i,uptime_ns=6135152000000i,version="4.0.19",vsize_megabytes=5088i 1595691605000000000 mongodb,hostname=127.0.0.1:27017,node_type=PRI,rs_name=rs0 active_reads=1i,assert_user=25i,commands=345i,connections_current=7i,document_inserted=2i,document_returned=56i,member_status="PRI",repl_lag=0i,repl_oplog_window_sec=140i,repl_state=1i,state="PRIMARY",uptime_ns=166481000000i,version="4.0.19" 1595691605000000000 mongodb_db_stats,db_name=admin,hostname=127.0.0.1:27017 avg_obj_size=241,collections=2i,data_size=723i,index_size=49152i,indexes=3i,num_extents=0i,objects=3i,ok=1i,storage_size=53248i,type="db_stat" 1547159491000000000 mongodb_db_stats,db_name=local,hostname=127.0.0.1:27017 avg_obj_size=813.9705882352941,collections=6i,data_size=55350i,index_size=102400i,indexes=5i,objects=68i,storage_size=204800i,type="db_stat" 1547159491000000000 mongodb_col_stats,collection=foo,db_name=local,hostname=127.0.0.1:27017 size=375005928i,avg_obj_size=5494,type="col_stat",storage_size=249307136i,total_index_size=2138112i,ok=1i,count=68251i 1547159491000000000 mongodb_shard_stats,hostname=127.0.0.1:27017,in_use=3i,available=3i,created=4i,refreshing=0i 1522799074000000000 mongodb_top_stats,collection=foo,total_time=1471,total_count=158,read_lock_time=49614,read_lock_count=657,write_lock_time=49125456,write_lock_count=9841,queries_time=174,queries_count=495,get_more_time=498,get_more_count=46,insert_time=2651,insert_count=1265,update_time=0,update_count=0,remove_time=0,remove_count=0,commands_time=498611,commands_count=4615

对比可发现:第二行是副本集成员,因此额外携带node_type=PRIrs_name=rs0标签以及member_statusstaterepl_lagrepl_oplog_window_secrepl_state等副本集字段;第一行单机节点则没有这些标签与字段。

快速验证与本地调试

仓库在 dev/ 目录提供了开箱即用的 Docker 联调环境,包含 docker-compose.yml 与 telegraf.conf:

# dev/docker-compose.yml services: mongodb: image: mongo telegraf: image: glinton/scratch volumes: - ./telegraf.conf:/telegraf.conf - ../../../../telegraf:/telegraf depends_on: - mongodb entrypoint: - /telegraf - --config - /telegraf.conf

对应的telegraf.conf设置 1 秒采集间隔、3 秒刷新间隔,采集mongodb://mongodb:27017并输出到 stdout,非常适合快速确认插件在本地环境的采集效果。

此外,mongodb_server_test.go 中基于 testcontainers 的集成测试(TestGetDefaultTagsIntegrationTestAddDefaultStatsIntegrationTestSkipBehaviorIntegration等)也展示了标准接入方式:构建MongoDB结构体 →Init()Start(&acc)→ 连续Gather→ 断言字段存在。日常排查时,还可以先用官方mongostatmongoshell 手动执行本文表格中的命令(如db.serverStatus()db.replSetGetStatus()db.top()),确认目标库具备相应权限后,再回到 Telegraf 侧观察指标输出。

结语

Telegraf 的 MongoDB 输入插件以官方数据库命令为数据源,通过两次采样差分模型,将mongostat式的实时状态转换为可长期存储、可绘制趋势图的时序指标,覆盖服务器健康、副本集同步、分片集群、数据库/集合容量与热点集合等核心监控场景。实际使用中,建议按需开启gather_perdb_statsgather_col_statsgather_top_stat(避免默认开启导致的额外开销),为采集账号授予clusterMonitor角色,并结合disconnected_servers_behaviordebug日志做好多节点、多副本集场景下的连接管理。

【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegraf

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询