You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ServiceMonitor是否支持为采集的指标添加自定义标签?

答案

完全可以直接在ServiceMonitor中完成自定义标签注入,不需要修改Spring Boot项目的任何代码,配置生效后Grafana就能直接基于新增的标签值做指标过滤。

ServiceMonitor是Prometheus Operator提供的抓取配置自定义资源,原生支持通过relabel(重标记)机制在指标抓取阶段注入标签,整个过程对应用侧完全透明,常用的配置场景分两类:

  • 注入固定值标签
    如果你需要给当前ServiceMonitor匹配的所有Spring Boot实例指标追加统一的固定标签,直接在对应抓取端点的relabelings字段下写规则即可,参考配置如下:
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: springboot-app-monitor
spec:
  selector:
    matchLabels:
      app: your-springboot-service # 匹配你Spring Boot应用对应的Service标签
  endpoints:
  - port: actuator # 对应Service暴露的actuator端口名
    path: /actuator/prometheus
    interval: 15s
    relabelings:
    # 追加固定标签env=prod
    - targetLabel: env
      replacement: prod
      action: replace
    # 追加固定标签biz_module=trade
    - targetLabel: biz_module
      replacement: trade
      action: replace

上述配置会给该端点抓到的所有指标自动带上你定义的两个固定标签,应用侧不需要做任何调整。

  • 从Kubernetes元数据同步标签
    如果你需要的标签值已经打在对应Pod/Service的标签、注解上,不需要硬编码固定值,也可以通过relabel规则直接把K8s元数据字段同步为指标标签,比如把Pod上的app_version标签同步到指标中:
relabelings:
- sourceLabels: [__meta_kubernetes_pod_label_app_version]
  targetLabel: app_version
  action: replace
配置校验提示
  • 配置完成后先到Prometheus的Targets页面找到对应Spring Boot应用的抓取任务,确认relabel规则已正确加载,再去Grafana做过滤配置,避免因为标签选择器写错、端口/路径不匹配导致规则不生效
  • 注意不要和Spring Boot应用侧埋点已经使用的标签名重名,否则会出现标签值覆盖的问题
  • 如果你需要给所有被Prometheus抓取的指标统一加全局公共标签,也可以直接在Prometheus自定义资源的spec.externalLabels字段配置,这种方式全局生效,适合加集群、环境这类通用标签。

内容的提问来源于stack exchange,提问作者Tomas Wen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 06:03:22