
Telegraf MongoDB 输入插件实战指南采集、指标解析与监控配置全解【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegrafTelegraf 官方 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_key10.10.3.30:27017, ## mongodb://10.10.3.33:18832, ## ## If connecting to a cluster, users must include the ?connectdirect 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/?connectdirect] ## 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 errorservers连接地址数组servers接受一组 MongoDB 连接 URL格式为mongodb:// [user : pass ] host [ : port]例如mongodb://user:auth_key10.10.3.30:27017带认证mongodb://10.10.3.33:18832自定义端口mongodb://127.0.0.1:27017/?connectdirect默认值连接集群时必须在 URL 中携带?connectdirect确保连接直达指定节点避免所有连接都被转发到主节点master node这对分片集群与副本集的多节点采集至关重要。插件在 mongodb.go 的setupConnection中会对未带 scheme 的主机名做向后兼容处理若 URL 不以mongodb://或mongodbsrv://开头会自动补全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_statsdbStats命令gather_col_statsfalse逐集合采集统计mongodb_col_statscollStats命令gather_top_statfalse采集每个集合的读写锁耗时等使用统计mongodb_top_statstop命令四个开关在 mongodb.go 中对应GatherClusterStatus、GatherPerDBStats、GatherColStats、GatherTopStat四个结构体字段。需要特别注意两点gather_cluster_status统计 jumbo chunks 的查询会触发COLLSCAN全集合扫描在数据量大的分片集群上可能带来性能影响默认虽然开启但生产环境需评估是否保留。gather_perdb_stats与gather_col_stats默认关闭因为它们需要对每个数据库/集合逐个执行命令数据库与集合数量较多时采集开销会明显上升。col_stats_dbs集合统计的数据库白名单当gather_col_stats true时用col_stats_dbs限定统计哪些数据库下的集合。若列表为空则统计所有数据库默认值为[local]。在 mongodb_server.go 的gatherCollectionStats中插件先列出所有数据库名再对命中的数据库过滤出type为collection或timeseries的集合跳过视图因为视图执行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_pwdCA 根证书、客户端证书、私钥及其加密密码。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.goerror默认任一台服务器启动时不可达Telegraf 直接返回启动错误。skip启动与每次采集时跳过不可达的服务器并在 Gather 阶段先ping探测失败则只记录 debug 日志、跳过该节点采集mongodb.go。此行为在 mongodb_server_test.go 中有集成测试验证skip模式下即使连接地址不可达Init、Start、Gather也不会报错。全局配置选项与所有 Telegraf 插件一样inputs.mongodb支持通用的全局与插件级配置例如使用namepass、fieldpass、tagexclude等对指标、标签、字段进行过滤与重命名或配置插件别名与执行顺序详见 docs/CONFIGURATION.md。权限要求与常见错误如果 MongoDB 实例开启了访问控制需要以具备足够权限的用户连接。MongoDB 3.4 及以上版本使用clusterMonitor角色即可覆盖本插件所需的serverStatus、replSetGetStatus、dbStats、collStats、top、connPoolStats等命令权限。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 的生命周期方法中Init校验disconnected_servers_behavior、构建 TLS 配置、补齐默认 servers。Start逐个 URL 调用setupConnection建立 MongoDB 连接mongo.Connect后Ping探测。Gather并发goroutine WaitGroup对每个已连接服务器执行gatherData。Stop带 10 秒超时断开所有连接用于插件重载/停止场景。gatherDatamongodb_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 数分片连接池shardConnPoolStatsMongoDB 5.0/connPoolStats≥ 5.0按版本选择命令见 mongodb_server.go数据库统计逐库执行dbStats受gather_perdb_stats控制集合统计逐集合执行collStats受gather_col_stats与col_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 的多个映射表中defaultStatsopcounters、游标、文档、连接等、defaultReplStats副本集、defaultClusterStats、defaultCommandsStats、defaultLatencyStats、defaultTCMallocStats、defaultStorageStats以及 WiredTiger 相关的wiredTigerStats/wiredTigerExtStats/wiredTigerConnectionStats/wiredTigerDataHandleStats。存储引擎相关字段如percent_cache_dirty、percent_cache_used及wtcache_*仅在存储引擎为wiredTiger时输出MMAPv1 引擎则输出mapped_megabytes、page_faults等字段mongodb_data.go。指标详解五类测量Measurementmongodb服务器整体状态tagshostname、node_type、rs_namehostname恒存在来自连接 URL 的主机:端口。node_type如PRI/SEC与rs_name副本集名称仅在服务器属于副本集时添加见 mongodb_data.go。fields节选核心项连接connections_current、connections_available、connections_total_created、open_connections操作计数inserts、queries、updates、deletes、getmores、commands、flushes后接_per_sec后缀的为速率字段如inserts_per_sec命令成功/失败aggregate_command_total/aggregate_command_failed、find_command_total/find_command_failed、insert_command_total/insert_command_failed、update_command_total/update_command_failed、delete_command_total/delete_command_failed、count_command_total/count_command_failed、distinct_command_total/distinct_command_failed、find_and_modify_command_total/find_and_modify_command_failed、get_more_command_total/get_more_command_failed延迟latency_reads/latency_reads_count、latency_writes/latency_writes_count、latency_commands/latency_commands_count读、写、命令总延迟及操作数可求平均值内存与缓存resident_megabytes、vsize_megabytes、percent_cache_dirty、percent_cache_used、page_faults游标cursor_total/cursor_total_count、cursor_timed_out/cursor_timed_out_count、cursor_no_timeout/cursor_no_timeout_count、cursor_pinned/cursor_pinned_countTTLttl_passes/ttl_passes_per_sec、ttl_deletes/ttl_deletes_per_sec文档操作document_inserted、document_updated、document_deleted、document_returned锁与并发active_reads、active_writes、queued_reads、queued_writes、available_reads、available_writes、total_tickets_reads、total_tickets_writes副本集member_status、state如PRIMARY、repl_state、repl_member_health、repl_health_avg、repl_lag、repl_oplog_window_sec以及repl_apply_*、repl_buffer_*、repl_executor_*、repl_network_*等存储storage_freelist_search_bucket_exhausted、storage_freelist_search_requests、storage_freelist_search_scannedWiredTigerwtcache_*系列缓存字节、页读入/写出、逐出统计等、wt_connection_files_currently_open、wt_data_handles_currently_activeTCMalloctcmalloc_*系列堆大小、pageheap 提交/释放/保留统计等其他assert_msg、assert_regular、assert_rollovers、assert_user、assert_warning、flushes_total_time_ns、jumbo_chunks、operation_scan_and_order、operation_write_conflicts、total_docs_scanned、total_keys_scanned、uptime_ns、version、net_in_bytes_count、net_out_bytes_count等1.10 版本的字段弃用说明一批_per_sec速率字段与部分累计字段自 Telegraf 1.10 起被弃用需改用对应的_count累计字段例如commands_per_sec→commands、cursor_total→cursor_total_count、net_in_bytes→net_in_bytes_count、repl_inserts_per_sec→repl_inserts。完整对应关系见 README 的 Metrics 列表新配置应直接使用新版字段。mongodb_db_stats按数据库统计tagsdb_name、hostnamefieldsavg_obj_size、collections、data_size、index_size、indexes、num_extents、objects、ok、storage_size、type固定为db_stat、fs_used_size、fs_total_size由dbStats命令驱动每个数据库输出一条记录适合观察各库的数据量与对象数增长。mongodb_col_stats按集合统计tagshostname、collection、db_namefieldssize、avg_obj_size、storage_size、total_index_size、ok、count、type固定为col_stat由collStats命令驱动受gather_col_stats与col_stats_dbs控制。可用于定位大集合、大索引与文档数增长。mongodb_shard_stats分片连接池统计tagshostnamefieldsin_use、available、created、refreshing由shardConnPoolStatsMongoDB 5.0或connPoolStats≥ 5.0命令驱动按分片主机输出连接池使用情况用于评估分片集群的连接饱和度。mongodb_top_stats集合使用统计tagscollectionfieldstotal_time、total_count、read_lock_time、read_lock_count、write_lock_time、write_lock_count、queries_time、queries_count、get_more_time、get_more_count、insert_time、insert_count、update_time、update_count、remove_time、remove_count、commands_time、commands_count由top命令驱动记录每个集合在读锁、写锁、查询、getmore、插入、更新、删除、命令等操作上花费的时间与次数用于定位热点集合。注意该命令在 mongodb_server.go 中的实现会先以map[string]interface{}接收原始返回剔除note键后再反序列化为结构化数据。输出示例以下为 README 中的真实输出样例influx line protocol节选展示了单机无副本集与副本集节点两类mongodb指标以及mongodb_db_stats、mongodb_col_stats、mongodb_shard_stats、mongodb_top_stats的典型形态mongodb,hostname127.0.0.1:27017 active_reads1i,active_writes0i,assert_msg0i,assert_regular0i,assert_user0i,available_reads127i,available_writes128i,commands65i,connections_available51199i,connections_current1i,connections_total_created5i,flushes52i,flushes_total_time_ns364000000i,inserts0i,jumbo_chunks0i,latency_commands5740i,latency_reads348i,open_connections1i,page_faults1i,percent_cache_dirty0,percent_cache_used0,queries1i,queued_reads0i,queued_writes0i,resident_megabytes33i,uptime_ns6135152000000i,version4.0.19,vsize_megabytes5088i 1595691605000000000 mongodb,hostname127.0.0.1:27017,node_typePRI,rs_namers0 active_reads1i,assert_user25i,commands345i,connections_current7i,document_inserted2i,document_returned56i,member_statusPRI,repl_lag0i,repl_oplog_window_sec140i,repl_state1i,statePRIMARY,uptime_ns166481000000i,version4.0.19 1595691605000000000 mongodb_db_stats,db_nameadmin,hostname127.0.0.1:27017 avg_obj_size241,collections2i,data_size723i,index_size49152i,indexes3i,num_extents0i,objects3i,ok1i,storage_size53248i,typedb_stat 1547159491000000000 mongodb_db_stats,db_namelocal,hostname127.0.0.1:27017 avg_obj_size813.9705882352941,collections6i,data_size55350i,index_size102400i,indexes5i,objects68i,storage_size204800i,typedb_stat 1547159491000000000 mongodb_col_stats,collectionfoo,db_namelocal,hostname127.0.0.1:27017 size375005928i,avg_obj_size5494,typecol_stat,storage_size249307136i,total_index_size2138112i,ok1i,count68251i 1547159491000000000 mongodb_shard_stats,hostname127.0.0.1:27017,in_use3i,available3i,created4i,refreshing0i 1522799074000000000 mongodb_top_stats,collectionfoo,total_time1471,total_count158,read_lock_time49614,read_lock_count657,write_lock_time49125456,write_lock_count9841,queries_time174,queries_count495,get_more_time498,get_more_count46,insert_time2651,insert_count1265,update_time0,update_count0,remove_time0,remove_count0,commands_time498611,commands_count4615对比可发现第二行是副本集成员因此额外携带node_typePRI、rs_namers0标签以及member_status、state、repl_lag、repl_oplog_window_sec、repl_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 的集成测试TestGetDefaultTagsIntegration、TestAddDefaultStatsIntegration、TestSkipBehaviorIntegration等也展示了标准接入方式构建MongoDB结构体 →Init()→Start(acc)→ 连续Gather→ 断言字段存在。日常排查时还可以先用官方mongostat或mongoshell 手动执行本文表格中的命令如db.serverStatus()、db.replSetGetStatus()、db.top()确认目标库具备相应权限后再回到 Telegraf 侧观察指标输出。结语Telegraf 的 MongoDB 输入插件以官方数据库命令为数据源通过两次采样差分模型将mongostat式的实时状态转换为可长期存储、可绘制趋势图的时序指标覆盖服务器健康、副本集同步、分片集群、数据库/集合容量与热点集合等核心监控场景。实际使用中建议按需开启gather_perdb_stats、gather_col_stats、gather_top_stat避免默认开启导致的额外开销为采集账号授予clusterMonitor角色并结合disconnected_servers_behavior与debug日志做好多节点、多副本集场景下的连接管理。【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegraf创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考