Metrics

Spring Boot Actuator 为 Micrometer提供依赖管理和自动配置,这是一个应用程序度量门面,支持 {url-micrometer-docs}[许多监视系统],包括:

Spring Boot Actuator provides dependency management and auto-configuration for Micrometer, an application metrics facade that supports {url-micrometer-docs}[numerous monitoring systems], including:

如需详细了解 Micrometer 的功能,请参阅其 {url-micrometer-docs}[参考文档],尤其是 {url-micrometer-docs-concepts}[概念部分]。

To learn more about Micrometer’s capabilities, see its {url-micrometer-docs}[reference documentation], in particular the {url-micrometer-docs-concepts}[concepts section].

Getting started

Spring Boot 会自动配置一个复合 MeterRegistry,并在复合中为在类路径中找到的每个受支持的实现添加一个注册表。在你的运行时类路径中对 `micrometer-registry-{system}`有依赖就足以让 Spring Boot 配置注册表。

Spring Boot auto-configures a composite MeterRegistry and adds a registry to the composite for each of the supported implementations that it finds on the classpath. Having a dependency on micrometer-registry-{system} in your runtime classpath is enough for Spring Boot to configure the registry.

大多数注册表共享通用特性。例如,即使 Micrometer 注册表实现位于类路径中,您也可以禁用特定注册表。下列示例禁用 Datadog:

Most registries share common features. For instance, you can disable a particular registry even if the Micrometer registry implementation is on the classpath. The following example disables Datadog:

management:
  datadog:
    metrics:
      export:
        enabled: false

您还可以禁用所有注册表,除非注册表特定属性另有规定,如下例所示:

You can also disable all registries unless stated otherwise by the registry-specific property, as the following example shows:

management:
  defaults:
    metrics:
      export:
        enabled: false

Spring Boot 还会将所有自动配置的注册表添加到 Metrics 类上的全局静态复合注册表中,除非您明确指示不这样做:

Spring Boot also adds any auto-configured registries to the global static composite registry on the Metrics class, unless you explicitly tell it not to:

management:
  metrics:
    use-global-registry: false

在用注册表注册任何仪表之前,您可以注册任意数量的 MeterRegistryCustomizer Bean 以进一步配置注册表,例如应用通用标记:

You can register any number of MeterRegistryCustomizer beans to further configure the registry, such as applying common tags, before any meters are registered with the registry:

通过指定泛型类型,您可以将自定义应用于特定注册表实现:

You can apply customizations to particular registry implementations by being more specific about the generic type:

Spring Boot 也会 configures built-in instrumentation ,您可以通过配置或专用注释标记来控制。

Spring Boot also configures built-in instrumentation that you can control through configuration or dedicated annotation markers.

Supported Monitoring Systems

本节简要介绍每个受支持的监控系统。

This section briefly describes each of the supported monitoring systems.

AppOptics

默认情况下,AppOptics 注册表会定期将指标推送到 https://api.appoptics.com/v1/measurements。要将指标导出到 SaaS {url-micrometer-docs-implementations}/appOptics[AppOptics],您必须提供 API 令牌:

By default, the AppOptics registry periodically pushes metrics to https://api.appoptics.com/v1/measurements. To export metrics to SaaS {url-micrometer-docs-implementations}/appOptics[AppOptics], your API token must be provided:

management:
  appoptics:
    metrics:
      export:
        api-token: "YOUR_TOKEN"

Atlas

默认情况下,指标会导出到本地机器上运行的 {url-micrometer-docs-implementations}/atlas[Atlas]。您可以提供 Atlas server 的位置:

By default, metrics are exported to {url-micrometer-docs-implementations}/atlas[Atlas] running on your local machine. You can provide the location of the Atlas server:

management:
  atlas:
    metrics:
      export:
        uri: "https://atlas.example.com:7101/api/v1/publish"

Datadog

Datadog 注册表会定期将指标推送到 datadoghq。要将指标导出到 {url-micrometer-docs-implementations}/datadog[Datadog],您必须提供 API 密钥:

A Datadog registry periodically pushes metrics to datadoghq. To export metrics to {url-micrometer-docs-implementations}/datadog[Datadog], you must provide your API key:

management:
  datadog:
    metrics:
      export:
        api-key: "YOUR_KEY"

如果您还提供了应用程序密钥(可选),诸如仪表描述、类型和基本单位等元数据也会被导出:

If you additionally provide an application key (optional), then metadata such as meter descriptions, types, and base units will also be exported:

management:
  datadog:
    metrics:
      export:
        api-key: "YOUR_API_KEY"
        application-key: "YOUR_APPLICATION_KEY"

默认情况下,指标会发送到 Datadog US site (https://api.datadoghq.com)。如果您的 Datadog 项目托管在其他站点之一,或者您需要通过代理发送指标,请相应地配置 URI:

By default, metrics are sent to the Datadog US site (https://api.datadoghq.com). If your Datadog project is hosted on one of the other sites, or you need to send metrics through a proxy, configure the URI accordingly:

management:
  datadog:
    metrics:
      export:
        uri: "https://api.datadoghq.eu"

您还可以更改发送指标到 Datadog 的间隔:

You can also change the interval at which metrics are sent to Datadog:

management:
  datadog:
    metrics:
      export:
        step: "30s"

Dynatrace

Dynatrace 提供了两个指标摄取 API,这两者都已为 {url-micrometer-docs-implementations}/dynatrace[Micrometer] 实现。您可以在 {url-dynatrace-docs-shortlink}/micrometer-metrics-ingest[此处] 找到 Dynatrace 关于 Micrometer 指标摄取的文档。v1 命名空间中的配置属性仅在导出到 {url-dynatrace-docs-shortlink}/api-metrics[时序 v1 API] 时适用。v2 命名空间中的配置属性仅在导出到 {url-dynatrace-docs-shortlink}/api-metrics-v2-post-datapoints[指标 v2 API] 时适用。请注意,此集成每次只能导出到 API 的 v1v2 版本,且首选 v2。如果在 v1 命名空间中设置了 device-id(v1 所需,但 v2 中未使用),指标将导出到 v1 端点。否则,假定为 v2

Dynatrace offers two metrics ingest APIs, both of which are implemented for {url-micrometer-docs-implementations}/dynatrace[Micrometer]. You can find the Dynatrace documentation on Micrometer metrics ingest {url-dynatrace-docs-shortlink}/micrometer-metrics-ingest[here]. Configuration properties in the v1 namespace apply only when exporting to the {url-dynatrace-docs-shortlink}/api-metrics[Timeseries v1 API]. Configuration properties in the v2 namespace apply only when exporting to the {url-dynatrace-docs-shortlink}/api-metrics-v2-post-datapoints[Metrics v2 API]. Note that this integration can export only to either the v1 or v2 version of the API at a time, with v2 being preferred. If the device-id (required for v1 but not used in v2) is set in the v1 namespace, metrics are exported to the v1 endpoint. Otherwise, v2 is assumed.

v2 API

您可以通过两种方式使用 v2 API。

You can use the v2 API in two ways.

Auto-configuration

对于由 OneAgent 或 Dynatrace Operator for Kubernetes 监控的主机,可以使用 Dynatrace 自动配置。

Dynatrace auto-configuration is available for hosts that are monitored by the OneAgent or by the Dynatrace Operator for Kubernetes.

Local OneAgent: 如果主机上正在运行 OneAgent,指标会自动导出到 {url-dynatrace-docs-shortlink}/local-api[本地 OneAgent 摄取端点]。摄取端点将指标转发到 Dynatrace 后端。

Local OneAgent: If a OneAgent is running on the host, metrics are automatically exported to the {url-dynatrace-docs-shortlink}/local-api[local OneAgent ingest endpoint]. The ingest endpoint forwards the metrics to the Dynatrace backend.

Dynatrace Kubernetes Operator: 当在已安装 Dynatrace 运算符的 Kubernetes 中运行时,注册表会自动从该运算符处获取你的端点 URI 和 API 令牌。

Dynatrace Kubernetes Operator: When running in Kubernetes with the Dynatrace Operator installed, the registry will automatically pick up your endpoint URI and API token from the operator instead.

这是默认行为,除了依赖于 `io.micrometer:micrometer-registry-dynatrace`之外,无需执行特殊设置。

This is the default behavior and requires no special setup beyond a dependency on io.micrometer:micrometer-registry-dynatrace.

Manual configuration

如果无法自动配置,则需要 {url-dynatrace-docs-shortlink}/api-metrics-v2-post-datapoints[Metrics v2 API] 的端点和一个 API 令牌。{url-dynatrace-docs-shortlink}/api-authentication[API 令牌] 必须设置有 “Ingest metrics” (metrics.ingest) 权限。我们建议将令牌的范围仅限于此权限。你必须确保端点 URI 包含路径(例如,/api/v2/metrics/ingest):

If no auto-configuration is available, the endpoint of the {url-dynatrace-docs-shortlink}/api-metrics-v2-post-datapoints[Metrics v2 API] and an API token are required. The {url-dynatrace-docs-shortlink}/api-authentication[API token] must have the “Ingest metrics” (metrics.ingest) permission set. We recommend limiting the scope of the token to this one permission. You must ensure that the endpoint URI contains the path (for example, /api/v2/metrics/ingest):

Metrics API v2 注入端点的 URL 根据你的部署选项而有所不同:

The URL of the Metrics API v2 ingest endpoint is different according to your deployment option:

以下示例使用 example 环境 ID 配置指标导出:

The example below configures metrics export using the example environment id:

management:
  dynatrace:
    metrics:
      export:
        uri: "https://example.live.dynatrace.com/api/v2/metrics/ingest"
        api-token: "YOUR_TOKEN"

在使用 Dynatrace v2 API 时,可以获得以下可选功能(更多详细信息,请参见 {url-dynatrace-docs-shortlink}/micrometer-metrics-ingest#dt-configuration-properties[Dynatrace 文档]):

When using the Dynatrace v2 API, the following optional features are available (more details can be found in the {url-dynatrace-docs-shortlink}/micrometer-metrics-ingest#dt-configuration-properties[Dynatrace documentation]):

  • Metric key prefix: Sets a prefix that is prepended to all exported metric keys.

  • Enrich with Dynatrace metadata: If a OneAgent or Dynatrace operator is running, enrich metrics with additional metadata (for example, about the host, process, or pod).

  • Default dimensions: Specify key-value pairs that are added to all exported metrics. If tags with the same key are specified with Micrometer, they overwrite the default dimensions.

  • Use Dynatrace Summary instruments: In some cases the Micrometer Dynatrace registry created metrics that were rejected. In Micrometer 1.9.x, this was fixed by introducing Dynatrace-specific summary instruments. Setting this toggle to false forces Micrometer to fall back to the behavior that was the default before 1.9.x. It should only be used when encountering problems while migrating from Micrometer 1.8.x to 1.9.x.

  • Export meter metadata: Starting from Micrometer 1.12.0, the Dynatrace exporter will also export meter metadata, such as unit and description by default. Use the export-meter-metadata toggle to turn this feature off.

可以不指定 URI 和 API 令牌,如下例所示。在此场景中,使用自动配置的端点:

It is possible to not specify a URI and API token, as shown in the following example. In this scenario, the automatically configured endpoint is used:

management:
  dynatrace:
    metrics:
      export:
        # Specify uri and api-token here if not using the local OneAgent endpoint.
        v2:
          metric-key-prefix: "your.key.prefix"
          enrich-with-dynatrace-metadata: true
          default-dimensions:
            key1: "value1"
            key2: "value2"
          use-dynatrace-summary-instruments: true # (default: true)
          export-meter-metadata: true             # (default: true)

v1 API (Legacy)

Dynatrace v1 API 指标注册表通过使用 {url-dynatrace-docs-shortlink}/api-metrics[Timeseries v1 API] 定期将指标推送至已配置的 URI。为了向后兼容现有设置,当设置 device-id 时(v1 所需,但在 v2 中不用),指标会被导出到 Timeseries v1 端点。若要将指标导出到 {url-micrometer-docs-implementations}/dynatrace[Dynatrace],必须提供 API 令牌、设备 ID 和 URI:

The Dynatrace v1 API metrics registry pushes metrics to the configured URI periodically by using the {url-dynatrace-docs-shortlink}/api-metrics[Timeseries v1 API]. For backwards-compatibility with existing setups, when device-id is set (required for v1, but not used in v2), metrics are exported to the Timeseries v1 endpoint. To export metrics to {url-micrometer-docs-implementations}/dynatrace[Dynatrace], your API token, device ID, and URI must be provided:

management:
  dynatrace:
    metrics:
      export:
        uri: "https://{your-environment-id}.live.dynatrace.com"
        api-token: "YOUR_TOKEN"
        v1:
          device-id: "YOUR_DEVICE_ID"

对于 v1 API,你必须指定没有路径的基本环境 URI,因为 v1 端点路径会自动添加。

For the v1 API, you must specify the base environment URI without a path, as the v1 endpoint path is added automatically.

Version-independent Settings

除了 API 端点和令牌以外,你还可以更改向 Dynatrace 发送指标的间隔。默认导出间隔为 60s。以下示例设置导出间隔为 30 秒:

In addition to the API endpoint and token, you can also change the interval at which metrics are sent to Dynatrace. The default export interval is 60s. The following example sets the export interval to 30 seconds:

management:
  dynatrace:
    metrics:
      export:
        step: "30s"

你可以在 {url-micrometer-docs-implementations}/dynatrace[Micrometer 文档] 和 {url-dynatrace-docs-shortlink}/micrometer-metrics-ingest[Dynatrace 文档] 中找到更多有关如何为 Micrometer 设置 Dynatrace 导出器的信息。

You can find more information on how to set up the Dynatrace exporter for Micrometer in the {url-micrometer-docs-implementations}/dynatrace[Micrometer documentation] and the {url-dynatrace-docs-shortlink}/micrometer-metrics-ingest[Dynatrace documentation].

Elastic

默认情况下,指标会导出到本地计算机上运行的 {url-micrometer-docs-implementations}/elastic[Elastic]。你可以使用以下属性提供要使用的 Elastic 服务器的位置:

By default, metrics are exported to {url-micrometer-docs-implementations}/elastic[Elastic] running on your local machine. You can provide the location of the Elastic server to use by using the following property:

management:
  elastic:
    metrics:
      export:
        host: "https://elastic.example.com:8086"

Ganglia

默认情况下,指标会导出到本地计算机上运行的 {url-micrometer-docs-implementations}/ganglia[Ganglia]。你可以提供 Ganglia server 主机和端口,如下例所示:

By default, metrics are exported to {url-micrometer-docs-implementations}/ganglia[Ganglia] running on your local machine. You can provide the Ganglia server host and port, as the following example shows:

management:
  ganglia:
    metrics:
      export:
        host: "ganglia.example.com"
        port: 9649

Graphite

默认情况下,指标会导出到本地计算机上运行的 {url-micrometer-docs-implementations}/graphite[Graphite]。你可以提供 Graphite server 主机和端口,如下例所示:

By default, metrics are exported to {url-micrometer-docs-implementations}/graphite[Graphite] running on your local machine. You can provide the Graphite server host and port, as the following example shows:

management:
  graphite:
    metrics:
      export:
         host: "graphite.example.com"
         port: 9004

Micrometer 提供一个默认的 HierarchicalNameMapper,它控制如何将一种维数计量器 ID {url-micrometer-docs-implementations}/graphite#_hierarchical_name_mapping[映射到平面层次结构名称]。

Micrometer provides a default HierarchicalNameMapper that governs how a dimensional meter ID is {url-micrometer-docs-implementations}/graphite#_hierarchical_name_mapping[mapped to flat hierarchical names].

要控制这种行为,请定义您的 GraphiteMeterRegistry`并提供自己的 `HierarchicalNameMapper。除非您定义自己的 `GraphiteConfig`和 `Clock`bean,否则会提供自动配置的 `GraphiteConfig`和 `Clock`bean:

To take control over this behavior, define your GraphiteMeterRegistry and supply your own HierarchicalNameMapper. An auto-configured GraphiteConfig and Clock beans are provided unless you define your own: include-code::MyGraphiteConfiguration[]

Humio

默认情况下,Humio 注册表会定期将指标推送到 [role="bare"][role="bare"]https://cloud.humio.com.要将指标导出到 SaaS {url-micrometer-docs-implementations}/humio[Humio],您必须提供您的 API 令牌:

By default, the Humio registry periodically pushes metrics to [role="bare"]https://cloud.humio.com. To export metrics to SaaS {url-micrometer-docs-implementations}/humio[Humio], you must provide your API token:

management:
  humio:
    metrics:
      export:
        api-token: "YOUR_TOKEN"

您还应配置一个或多个标签,以识别要将指标推送到其上的数据源:

You should also configure one or more tags to identify the data source to which metrics are pushed:

management:
  humio:
    metrics:
      export:
        tags:
          alpha: "a"
          bravo: "b"

Influx

默认情况下,指标将被导出到本地计算机上具有默认配置的 {url-micrometer-docs-implementations}/influx[Influx] v1 实例。要将指标导出到 InfluxDB v2,请为写入指标配置 orgbucket,以及进行身份验证的 token。您可以使用以下方法提供要使用的 Influx server的位置:

By default, metrics are exported to an {url-micrometer-docs-implementations}/influx[Influx] v1 instance running on your local machine with the default configuration. To export metrics to InfluxDB v2, configure the org, bucket, and authentication token for writing metrics. You can provide the location of the Influx server to use by using:

management:
  influx:
    metrics:
      export:
        uri: "https://influx.example.com:8086"

JMX

Micrometer 提供到 {url-micrometer-docs-implementations}/jmx[JMX] 的一个层次结构映射,主要是作为一种低成本且可移植的方式在本地查看指标。默认情况下,指标会导出到 `metrics`JMX 域。您可以使用以下方法提供要使用的域:

Micrometer provides a hierarchical mapping to {url-micrometer-docs-implementations}/jmx[JMX], primarily as a cheap and portable way to view metrics locally. By default, metrics are exported to the metrics JMX domain. You can provide the domain to use by using:

management:
  jmx:
    metrics:
      export:
        domain: "com.example.app.metrics"

Micrometer 提供一个默认的 HierarchicalNameMapper,它控制如何将一种维数计量器 ID {url-micrometer-docs-implementations}/jmx#_hierarchical_name_mapping[映射到平面层次结构名称]。

Micrometer provides a default HierarchicalNameMapper that governs how a dimensional meter ID is {url-micrometer-docs-implementations}/jmx#_hierarchical_name_mapping[mapped to flat hierarchical names].

要控制这种行为,请定义您的 JmxMeterRegistry`并提供自己的 `HierarchicalNameMapper。除非您定义自己的 `JmxConfig`和 `Clock`bean,否则会提供自动配置的 `JmxConfig`和 `Clock`bean:

To take control over this behavior, define your JmxMeterRegistry and supply your own HierarchicalNameMapper. An auto-configured JmxConfig and Clock beans are provided unless you define your own: include-code::MyJmxConfiguration[]

KairosDB

默认情况下,指标会导出到本地计算机上运行的 {url-micrometer-docs-implementations}/kairos[KairosDB]。您可以使用以下方法提供要使用的 KairosDB server的位置:

By default, metrics are exported to {url-micrometer-docs-implementations}/kairos[KairosDB] running on your local machine. You can provide the location of the KairosDB server to use by using:

management:
  kairos:
    metrics:
      export:
        uri: "https://kairosdb.example.com:8080/api/v1/datapoints"

New Relic

New Relic 注册表会定期将指标推送到 {url-micrometer-docs-implementations}/new-relic[New Relic]。要将指标添加到 New Relic,您必须提供您的 API 密钥和帐户 ID:

A New Relic registry periodically pushes metrics to {url-micrometer-docs-implementations}/new-relic[New Relic]. To export metrics to New Relic, you must provide your API key and account ID:

management:
  newrelic:
    metrics:
      export:
        api-key: "YOUR_KEY"
        account-id: "YOUR_ACCOUNT_ID"

您还可以更改指标发送给 New Relic 的时间间隔:

You can also change the interval at which metrics are sent to New Relic:

management:
  newrelic:
    metrics:
      export:
        step: "30s"

默认情况下,指标通过 REST 调用发布,但如果您在 classpath 中有的话,您还可以使用 Java Agent API:

By default, metrics are published through REST calls, but you can also use the Java Agent API if you have it on the classpath:

management:
  newrelic:
    metrics:
      export:
        client-provider-type: "insights-agent"

最后,您可以通过定义自己的 `NewRelicClientProvider`bean 来完全控制。

Finally, you can take full control by defining your own NewRelicClientProvider bean.

OpenTelemetry

默认情况下,指标会导出到本地计算机上运行的 {url-micrometer-docs-implementations}/otlp[OpenTelemetry]。您可以使用以下方法提供要使用的 OpenTelemetry metric endpoint的位置:

By default, metrics are exported to {url-micrometer-docs-implementations}/otlp[OpenTelemetry] running on your local machine. You can provide the location of the OpenTelemetry metric endpoint to use by using:

management:
  otlp:
    metrics:
      export:
        url: "https://otlp.example.com:4318/v1/metrics"

Prometheus

{url-micrometer-docs-implementations}/prometheus[Prometheus] 期望为指标抓取或轮询各个应用程序实例。Spring Boot 在 `/actuator/prometheus`提供了一个 actuator 终结点,以使用适当的格式展示 Prometheus scrape

{url-micrometer-docs-implementations}/prometheus[Prometheus] expects to scrape or poll individual application instances for metrics. Spring Boot provides an actuator endpoint at /actuator/prometheus to present a Prometheus scrape with the appropriate format.

默认情况下,端点不可用且不得公开。有关详细信息,请参阅 exposing endpoints

By default, the endpoint is not available and must be exposed. See exposing endpoints for more details.

以下示例 scrape_config`添加到 `prometheus.yml

The following example scrape_config adds to prometheus.yml:

scrape_configs:
- job_name: "spring"
  metrics_path: "/actuator/prometheus"
  static_configs:
  - targets: ["HOST:PORT"]

Prometheus Exemplars也受支持。要启用此功能,应该存在 `SpanContextSupplier`Bean。如果您使用 Micrometer Tracing, 系统会自动为您配置该功能,但您始终可以创建您自己的功能(如果您愿意)。请查看 Prometheus Docs,因为此功能需要在 Prometheus 的服务器端显式启用,并且仅支持使用 OpenMetrics格式。

Prometheus Exemplars are also supported. To enable this feature, a SpanContextSupplier bean should be present. If you use Micrometer Tracing, this will be auto-configured for you, but you can always create your own if you want. Please check the Prometheus Docs, since this feature needs to be explicitly enabled on Prometheus' side, and it is only supported using the OpenMetrics format.

对于可能不存在足够长的时间以被刮取的临时或批处理作业,您可以使用 Prometheus Pushgateway支持向 Prometheus 公开指标。要启用 Prometheus Pushgateway 支持,请将以下依赖项添加到您的项目:

For ephemeral or batch jobs that may not exist long enough to be scraped, you can use Prometheus Pushgateway support to expose the metrics to Prometheus. To enable Prometheus Pushgateway support, add the following dependency to your project:

<dependency>
	<groupId>io.prometheus</groupId>
	<artifactId>simpleclient_pushgateway</artifactId>
</dependency>

当类路径中存在 Prometheus Pushgateway 依赖项时,且 configprop:management.prometheus.metrics.export.pushgateway.enabled[] 属性设置为 `true`时,会自动配置 `PrometheusPushGatewayManager`bean. 这管理将指标推送到 Prometheus Pushgateway。

When the Prometheus Pushgateway dependency is present on the classpath and the configprop:management.prometheus.metrics.export.pushgateway.enabled[] property is set to true, a PrometheusPushGatewayManager bean is auto-configured. This manages the pushing of metrics to a Prometheus Pushgateway.

您可以通过使用 management.prometheus.metrics.export.pushgateway`下的属性来调整 `PrometheusPushGatewayManager。对于高级配置,您还可以提供您自己的 `PrometheusPushGatewayManager`bean。

You can tune the PrometheusPushGatewayManager by using properties under management.prometheus.metrics.export.pushgateway. For advanced configuration, you can also provide your own PrometheusPushGatewayManager bean.

SignalFx

SignalFx 注册表定期将指标推送到 {url-micrometer-docs-implementations}/signalFx[SignalFx]。要将指标导出到 SignalFx, 您必须提供您的访问令牌:

SignalFx registry periodically pushes metrics to {url-micrometer-docs-implementations}/signalFx[SignalFx]. To export metrics to SignalFx, you must provide your access token:

management:
  signalfx:
    metrics:
      export:
        access-token: "YOUR_ACCESS_TOKEN"

您还可以更改发送指标至 SignalFx 的时间间隔:

You can also change the interval at which metrics are sent to SignalFx:

management:
  signalfx:
    metrics:
      export:
        step: "30s"

Simple

Micrometer 附带了一个简单的内存后端,如果未配置任何其他注册表,则会自动使用它作为一个后备。这允许您查看在 metrics endpoint中收集了哪些指标。

Micrometer ships with a simple, in-memory backend that is automatically used as a fallback if no other registry is configured. This lets you see what metrics are collected in the metrics endpoint.

一旦您使用任何其他可用的后端,内存后端就会自动禁用自身。您也可以显式禁用它:

The in-memory backend disables itself as soon as you use any other available backend. You can also disable it explicitly:

management:
  simple:
    metrics:
      export:
        enabled: false

Stackdriver

Stackdriver 注册表定期将指标推送到 Stackdriver。要将指标导出到 SaaS {url-micrometer-docs-implementations}/stackdriver[Stackdriver],您必须提供您的 Google Cloud 项目 ID:

The Stackdriver registry periodically pushes metrics to Stackdriver. To export metrics to SaaS {url-micrometer-docs-implementations}/stackdriver[Stackdriver], you must provide your Google Cloud project ID:

management:
  stackdriver:
    metrics:
      export:
        project-id: "my-project"

您还可以更改发送指标至 Stackdriver 的时间间隔:

You can also change the interval at which metrics are sent to Stackdriver:

management:
  stackdriver:
    metrics:
      export:
        step: "30s"

StatsD

StatsD 注册表急切地通过 UDP 将指标推送到 StatsD 代理。默认情况下,指标将导出到运行在您的本地计算机上的一个 {url-micrometer-docs-implementations}/statsD[StatsD] 代理。您可以通过使用以下内容来提供要使用的 StatsD 代理主机、端口和协议:

The StatsD registry eagerly pushes metrics over UDP to a StatsD agent. By default, metrics are exported to a {url-micrometer-docs-implementations}/statsD[StatsD] agent running on your local machine. You can provide the StatsD agent host, port, and protocol to use by using:

management:
  statsd:
    metrics:
      export:
        host: "statsd.example.com"
        port: 9125
        protocol: "udp"

您还可以更改要使用的 StatsD 行协议(它默认为 Datadog):

You can also change the StatsD line protocol to use (it defaults to Datadog):

management:
  statsd:
    metrics:
      export:
        flavor: "etsy"

Wavefront

Wavefront 注册表定期将指标推送到 {url-micrometer-docs-implementations}/wavefront[Wavefront]。如果您直接将指标导出到 Wavefront, 则必须提供您的 API 令牌:

The Wavefront registry periodically pushes metrics to {url-micrometer-docs-implementations}/wavefront[Wavefront]. If you are exporting metrics to Wavefront directly, you must provide your API token:

management:
  wavefront:
    api-token: "YOUR_API_TOKEN"

或者,您可以在您的环境中使用 Wavefront 边车或内部代理将指标数据转发至 Wavefront API 主机:

Alternatively, you can use a Wavefront sidecar or an internal proxy in your environment to forward metrics data to the Wavefront API host:

management:
  wavefront:
    uri: "proxy://localhost:2878"

如果您将指标发布到 Wavefront 代理(如 the Wavefront documentation中所述),则主机必须采用 `proxy://HOST:PORT`格式。

If you publish metrics to a Wavefront proxy (as described in the Wavefront documentation), the host must be in the proxy://HOST:PORT format.

您还可以更改发送指标至 Wavefront 的时间间隔:

You can also change the interval at which metrics are sent to Wavefront:

management:
  wavefront:
    metrics:
      export:
        step: "30s"

Supported Metrics and Meters

Spring Boot 为各种技术提供自动仪表注册。在大多数情况下,默认值会提供合理的指标,这些指标可以发布到任何受支持的监控系统。

Spring Boot provides automatic meter registration for a wide variety of technologies. In most situations, the defaults provide sensible metrics that can be published to any of the supported monitoring systems.

JVM Metrics

自动配置通过使用核心 Micrometer 类来启用 JVM 指标。JVM 指标以 `jvm.`仪表名称发布。

Auto-configuration enables JVM Metrics by using core Micrometer classes. JVM metrics are published under the jvm. meter name.

提供下列 JVM 指标:

The following JVM metrics are provided:

  • Various memory and buffer pool details

  • Statistics related to garbage collection

  • Thread utilization

  • The number of classes loaded and unloaded

  • JVM version information

  • JIT compilation time

System Metrics

自动配置通过使用核心 Micrometer 类来启用系统指标。系统指标以 system.、`process.`和 `disk.`仪表名称发布。

Auto-configuration enables system metrics by using core Micrometer classes. System metrics are published under the system., process., and disk. meter names.

提供下列系统指标:

The following system metrics are provided:

  • CPU metrics

  • File descriptor metrics

  • Uptime metrics (both the amount of time the application has been running and a fixed gauge of the absolute start time)

  • Disk space available

Application Startup Metrics

自动配置公开应用程序启动时间指标:

Auto-configuration exposes application startup time metrics:

  • application.started.time: time taken to start the application.

  • application.ready.time: time taken for the application to be ready to service requests.

指标加上了应用程序类的完全限定名的标签。

Metrics are tagged by the fully qualified name of the application class.

Logger Metrics

自动配置为 Logback 和 Log4J2 启用事件指标。详细信息以 `log4j2.events.`或 `logback.events.`仪表名称发布。

Auto-configuration enables the event metrics for both Logback and Log4J2. The details are published under the log4j2.events. or logback.events. meter names.

Task Execution and Scheduling Metrics

自动配置为所有可用的 `ThreadPoolTaskExecutor`和 `ThreadPoolTaskScheduler`bean 启用检测,只要底层 `ThreadPoolExecutor`可用即可。指标加上了执行器名称的标签,该名称来自 bean 名称。

Auto-configuration enables the instrumentation of all available ThreadPoolTaskExecutor and ThreadPoolTaskScheduler beans, as long as the underling ThreadPoolExecutor is available. Metrics are tagged by the name of the executor, which is derived from the bean name.

JMS Metrics

自动配置为所有可用的 `JmsTemplate`bean 和 `@JmsListener`注释方法启用检测。这将分别生成 `"jms.message.publish"`和 `"jms.message.process"`指标。有关生成观测的详细信息,请参阅 {url-spring-framework-docs}/integration/observability.html#observability.jms[Spring Framework 参考文档]。

Auto-configuration enables the instrumentation of all available JmsTemplate beans and @JmsListener annotated methods. This will produce "jms.message.publish" and "jms.message.process" metrics respectively. See the {url-spring-framework-docs}/integration/observability.html#observability.jms[Spring Framework reference documentation for more information on produced observations].

Spring MVC Metrics

自动配置为 Spring MVC 控制器和函数式处理程序处理的所有请求启用检测。默认情况下,指标以名称 `http.server.requests`生成。您可以通过设置 configprop:management.observations.http.server.requests.name[] 属性来自定义名称。

Auto-configuration enables the instrumentation of all requests handled by Spring MVC controllers and functional handlers. By default, metrics are generated with the name, http.server.requests. You can customize the name by setting the configprop:management.observations.http.server.requests.name[] property.

有关生成观测的详细信息,请参阅 {url-spring-framework-docs}/integration/observability.html#observability.http-server.servlet[Spring Framework 参考文档]。

See the {url-spring-framework-docs}/integration/observability.html#observability.http-server.servlet[Spring Framework reference documentation for more information on produced observations].

若要添加到默认标签,请提供一个从 org.springframework.http.server.observation`包中的 `DefaultServerRequestObservationConvention`扩展的 `@Bean。若要替换默认标签,请提供一个实现 ServerRequestObservationConvention`的 `@Bean

To add to the default tags, provide a @Bean that extends DefaultServerRequestObservationConvention from the org.springframework.http.server.observation package. To replace the default tags, provide a @Bean that implements ServerRequestObservationConvention.

在某些情况下,web 控制器中处理的异常不会记录为请求指标标签。应用程序可以选择启用并记录 setting handled exceptions as request attributes的异常。

In some cases, exceptions handled in web controllers are not recorded as request metrics tags. Applications can opt in and record exceptions by setting handled exceptions as request attributes.

默认情况下,所有请求都处理。要自定义筛选,可提供实现`FilterRegistrationBean<ServerHttpObservationFilter>`的`@Bean`。

By default, all requests are handled. To customize the filter, provide a @Bean that implements FilterRegistrationBean<ServerHttpObservationFilter>.

Spring WebFlux Metrics

自动配置可以 对 Spring WebFlux 控制器和函数式处理程序所处理的所有请求进行仪器检查。默认情况下,度量以名称生成,http.server.requests。可以通过设置 configprop:management.observations.http.server.requests.name[] 属性来自定义名称。

Auto-configuration enables the instrumentation of all requests handled by Spring WebFlux controllers and functional handlers. By default, metrics are generated with the name, http.server.requests. You can customize the name by setting the configprop:management.observations.http.server.requests.name[] property.

有关生成观察的更多信息,请参阅 {url-spring-framework-docs}/integration/observability.html#observability.http-server.reactive[Spring 框架参考文档]。

See the {url-spring-framework-docs}/integration/observability.html#observability.http-server.reactive[Spring Framework reference documentation for more information on produced observations].

要添加到默认标记,可提供从`org.springframework.http.server.reactive.observation`包中扩展`DefaultServerRequestObservationConvention`的`@Bean`。要替换默认标记,可提供实现`ServerRequestObservationConvention`的`@Bean`。

To add to the default tags, provide a @Bean that extends DefaultServerRequestObservationConvention from the org.springframework.http.server.reactive.observation package. To replace the default tags, provide a @Bean that implements ServerRequestObservationConvention.

在某些情况下,在控制器和处理程序函数中处理的异常不会被记录为请求度量标记。应用程序可以通过setting handled exceptions as request attributes选择并记录异常。

In some cases, exceptions handled in controllers and handler functions are not recorded as request metrics tags. Applications can opt in and record exceptions by setting handled exceptions as request attributes.

Jersey Server Metrics

自动配置可以 对 Jersey JAX-RS 实现所处理的所有请求进行仪器检查。默认情况下,度量以名称生成,http.server.requests。可以通过设置 configprop:management.observations.http.server.requests.name[] 属性来自定义名称。

Auto-configuration enables the instrumentation of all requests handled by the Jersey JAX-RS implementation. By default, metrics are generated with the name, http.server.requests. You can customize the name by setting the configprop:management.observations.http.server.requests.name[] property.

默认情况下,Jersey 服务器度量标记有以下信息:

By default, Jersey server metrics are tagged with the following information:

Tag Description

exception

The simple class name of any exception that was thrown while handling the request.

method

The request’s method (for example, GET or POST)

outcome

The request’s outcome, based on the status code of the response. 1xx is INFORMATIONAL, 2xx is SUCCESS, 3xx is REDIRECTION, 4xx is CLIENT_ERROR, and 5xx is SERVER_ERROR

status

The response’s HTTP status code (for example, 200 or 500)

uri

The request’s URI template prior to variable substitution, if possible (for example, /api/person/{id})

要自定义标记,可提供实现`JerseyObservationConvention`的`@Bean`。

To customize the tags, provide a @Bean that implements JerseyObservationConvention.

HTTP Client Metrics

Spring Boot Actuator 管理`RestTemplate`、`WebClient`和`RestClient`的仪器检查。为此,你必须注入自动配置的生成器并使用它来创建实例:

Spring Boot Actuator manages the instrumentation of RestTemplate, WebClient and RestClient. For that, you have to inject the auto-configured builder and use it to create instances:

  • RestTemplateBuilder for RestTemplate

  • WebClient.Builder for WebClient

  • RestClient.Builder for RestClient

你还可以手动应用对此仪器检查负责的自定义器,即 ObservationRestTemplateCustomizerObservationWebClientCustomizer`和`ObservationRestClientCustomizer

You can also manually apply the customizers responsible for this instrumentation, namely ObservationRestTemplateCustomizer, ObservationWebClientCustomizer and ObservationRestClientCustomizer.

默认情况下,度量以名称生成,http.client.requests。可以通过设置 configprop:management.observations.http.client.requests.name[] 属性来自定义名称。

By default, metrics are generated with the name, http.client.requests. You can customize the name by setting the configprop:management.observations.http.client.requests.name[] property.

有关生成观察的更多信息,请参阅 {url-spring-framework-docs}/integration/observability.html#observability.http-client[Spring 框架参考文档]。

See the {url-spring-framework-docs}/integration/observability.html#observability.http-client[Spring Framework reference documentation for more information on produced observations].

要自定义使用`RestTemplate`或`RestClient`时的标记,可提供从`org.springframework.http.client.observation`包中实现`ClientRequestObservationConvention`的`@Bean`。要自定义使用`WebClient`时的标记,可提供从`org.springframework.web.reactive.function.client`包中实现`ClientRequestObservationConvention`的`@Bean`。

To customize the tags when using RestTemplate or RestClient, provide a @Bean that implements ClientRequestObservationConvention from the org.springframework.http.client.observation package. To customize the tags when using WebClient, provide a @Bean that implements ClientRequestObservationConvention from the org.springframework.web.reactive.function.client package.

Tomcat Metrics

只有在启用`MBeanRegistry`时,自动配置才会启用 Tomcat 的仪器检查。默认情况下,`MBeanRegistry`处于禁用状态,但可以通过将 configprop:server.tomcat.mbeanregistry.enabled[] 设置为 `true`来启用它。

Auto-configuration enables the instrumentation of Tomcat only when an MBeanRegistry is enabled. By default, the MBeanRegistry is disabled, but you can enable it by setting configprop:server.tomcat.mbeanregistry.enabled[] to true.

Tomcat 指标在 tomcat. 仪表名称下发布。

Tomcat metrics are published under the tomcat. meter name.

Cache Metrics

自动配置启用在启动时对所有可用的 Cache 实例进行检测,并为指标添加 cache 前缀。Cache 检测针对一组基本指标进行了标准化。还可使用额外的,特定于缓存的指标。

Auto-configuration enables the instrumentation of all available Cache instances on startup, with metrics prefixed with cache. Cache instrumentation is standardized for a basic set of metrics. Additional, cache-specific metrics are also available.

支持以下缓存库:

The following cache libraries are supported:

  • Cache2k

  • Caffeine

  • Hazelcast

  • Any compliant JCache (JSR-107) implementation

  • Redis

指标通过缓存名称和 CacheManager 名称进行标记,后者派生自 Bean 名称。

Metrics are tagged by the name of the cache and by the name of the CacheManager, which is derived from the bean name.

仅在启动时配置的缓存与注册表绑定。对于缓存配置中未定义的缓存(例如在启动阶段后动态创建或通过编程创建的缓存),需要显式注册。CacheMetricsRegistrar Bean 可用于简化该过程。

Only caches that are configured on startup are bound to the registry. For caches not defined in the cache’s configuration, such as caches created on the fly or programmatically after the startup phase, an explicit registration is required. A CacheMetricsRegistrar bean is made available to make that process easier.

Spring Batch Metrics

请参阅 {url-spring-batch-docs}/monitoring-and-metrics.html[Spring Batch 参考文档]。

See the {url-spring-batch-docs}/monitoring-and-metrics.html[Spring Batch reference documentation].

Spring GraphQL Metrics

请参阅 {url-spring-graphql-docs}/observability.html[Spring GraphQL 参考文档]。

See the {url-spring-graphql-docs}/observability.html[Spring GraphQL reference documentation].

DataSource Metrics

自动配置启用对所有可用的 DataSource 对象进行检测,并为指标添加 jdbc.connections 前缀。数据源检测会导致仪表表示连接池中当前处于活动状态、空闲状态、允许的最大连接数和允许的最小连接数。

Auto-configuration enables the instrumentation of all available DataSource objects with metrics prefixed with jdbc.connections. Data source instrumentation results in gauges that represent the currently active, idle, maximum allowed, and minimum allowed connections in the pool.

指标还通过根据 Bean 名称计算的 DataSource 名称进行标记。

Metrics are also tagged by the name of the DataSource computed based on the bean name.

默认情况下,Spring Boot 为所有受支持的数据源提供元数据。如果您的首选数据源不受支持,则可以添加其他 DataSourcePoolMetadataProvider Bean。有关示例,请参见 DataSourcePoolMetadataProvidersConfiguration

By default, Spring Boot provides metadata for all supported data sources. You can add additional DataSourcePoolMetadataProvider beans if your favorite data source is not supported. See DataSourcePoolMetadataProvidersConfiguration for examples.

此外,以 hikaricp 前缀展示特定的 Hikari 指标。每个指标均通过池名称进行标记(您可以使用 spring.datasource.name 控制该池名称)。

Also, Hikari-specific metrics are exposed with a hikaricp prefix. Each metric is tagged by the name of the pool (you can control it with spring.datasource.name).

Hibernate Metrics

如果 org.hibernate.orm:hibernate-micrometer 位于类路径中,则会检测所有可用的启用统计信息的 Hibernate EntityManagerFactory 实例,并为这些实例检测名为 hibernate 的指标。

If org.hibernate.orm:hibernate-micrometer is on the classpath, all available Hibernate EntityManagerFactory instances that have statistics enabled are instrumented with a metric named hibernate.

指标还通过根据 Bean 名称派生的 EntityManagerFactory 名称进行标记。

Metrics are also tagged by the name of the EntityManagerFactory, which is derived from the bean name.

要启用统计信息,必须将标准 JPA 属性 hibernate.generate_statistics 设置为 true。可以在自动配置的 EntityManagerFactory 上启用该属性:

To enable statistics, the standard JPA property hibernate.generate_statistics must be set to true. You can enable that on the auto-configured EntityManagerFactory:

spring:
  jpa:
    properties:
      "[hibernate.generate_statistics]": true

Spring Data Repository Metrics

自动配置启用对所有 Spring Data Repository 方法调用的检测。默认情况下,会生成带有名称 spring.data.repository.invocations 的指标。可以通过设置 configprop:management.metrics.data.repository.metric-name[] 属性来自定义名称。

Auto-configuration enables the instrumentation of all Spring Data Repository method invocations. By default, metrics are generated with the name, spring.data.repository.invocations. You can customize the name by setting the configprop:management.metrics.data.repository.metric-name[] property.

@Timed 包中的 io.micrometer.core.annotation 注释在 Repository 接口和方法上受支持。如果您不想为所有 Repository 调用记录指标,则可以将 configprop:management.metrics.data.repository.autotime.enabled[] 设置为 false,并仅独家使用 @Timed 注释。

The @Timed annotation from the io.micrometer.core.annotation package is supported on Repository interfaces and methods. If you do not want to record metrics for all Repository invocations, you can set configprop:management.metrics.data.repository.autotime.enabled[] to false and exclusively use @Timed annotations instead.

具有 longTask = true@Timed 注释为该方法启用了一个长任务计时器。长任务计时器需要独立的指标名称,并且可以与短任务计时器一起使用。

A @Timed annotation with longTask = true enables a long task timer for the method. Long task timers require a separate metric name and can be stacked with a short task timer.

默认情况下,与存储库调用相关的指标通过以下信息进行标记:

By default, repository invocation related metrics are tagged with the following information:

Tag Description

repository

The simple class name of the source Repository.

method

The name of the Repository method that was invoked.

state

The result state (SUCCESS, ERROR, CANCELED, or RUNNING).

exception

The simple class name of any exception that was thrown from the invocation.

要替换默认标记,请提供实现 RepositoryTagsProvider`的 `@Bean

To replace the default tags, provide a @Bean that implements RepositoryTagsProvider.

RabbitMQ Metrics

自动配置使用名为 `rabbitmq`的指标启用所有可用 RabbitMQ 连接工厂的检测功能。

Auto-configuration enables the instrumentation of all available RabbitMQ connection factories with a metric named rabbitmq.

Spring Integration Metrics

只要有 `MeterRegistry`bean,Spring 集成就会自动提供 {url-spring-integration-docs}/metrics.html#micrometer-integration[Micrometer 支持]。指标发布在 `spring.integration.`度量器名称下。

Spring Integration automatically provides {url-spring-integration-docs}/metrics.html#micrometer-integration[Micrometer support] whenever a MeterRegistry bean is available. Metrics are published under the spring.integration. meter name.

Kafka Metrics

自动配置分别为自动配置的使用者工厂和生产者工厂注册 MicrometerConsumerListener`和 `MicrometerProducerListener。它还为 StreamsBuilderFactoryBean`注册 `KafkaStreamsMicrometerListener。有关更多详情,请参阅 Spring Kafka 文档的 {url-spring-kafka-docs}/kafka/micrometer.html#micrometer-native[Micrometer 本机指标] 部分。

Auto-configuration registers a MicrometerConsumerListener and MicrometerProducerListener for the auto-configured consumer factory and producer factory, respectively. It also registers a KafkaStreamsMicrometerListener for StreamsBuilderFactoryBean. For more detail, see the {url-spring-kafka-docs}/kafka/micrometer.html#micrometer-native[Micrometer Native Metrics] section of the Spring Kafka documentation.

MongoDB Metrics

本节简要介绍 MongoDB 可用的指标。

This section briefly describes the available metrics for MongoDB.

MongoDB Command Metrics

自动配置用自动配置的 MongoClient`注册 `MongoMetricsCommandListener

Auto-configuration registers a MongoMetricsCommandListener with the auto-configured MongoClient.

针对发给底层 MongoDB 驱动程序的每条命令创建一个名为 `mongodb.driver.commands`的计时器指标。默认情况下,每个指标都会标记以下信息:

A timer metric named mongodb.driver.commands is created for each command issued to the underlying MongoDB driver. Each metric is tagged with the following information by default:

Tag Description

command

The name of the command issued.

cluster.id

The identifier of the cluster to which the command was sent.

server.address

The address of the server to which the command was sent.

status

The outcome of the command (SUCCESS or FAILED).

要替换默认指标标记,请定义 `MongoCommandTagsProvider`bean,如下例所示:

To replace the default metric tags, define a MongoCommandTagsProvider bean, as the following example shows:

要禁用自动配置的命令指标,请设置以下属性:

To disable the auto-configured command metrics, set the following property:

management:
  metrics:
    mongo:
      command:
        enabled: false

MongoDB Connection Pool Metrics

自动配置用自动配置的 MongoClient`注册 `MongoMetricsConnectionPoolListener

Auto-configuration registers a MongoMetricsConnectionPoolListener with the auto-configured MongoClient.

为连接池创建了以下仪表指标:

The following gauge metrics are created for the connection pool:

  • mongodb.driver.pool.size reports the current size of the connection pool, including idle and and in-use members.

  • mongodb.driver.pool.checkedout reports the count of connections that are currently in use.

  • mongodb.driver.pool.waitqueuesize reports the current size of the wait queue for a connection from the pool.

默认情况下,每个指标都标记为以下信息:

Each metric is tagged with the following information by default:

Tag Description

cluster.id

The identifier of the cluster to which the connection pool corresponds.

server.address

The address of the server to which the connection pool corresponds.

要替换默认指标标签,请定义一个 MongoConnectionPoolTagsProvider bean:

To replace the default metric tags, define a MongoConnectionPoolTagsProvider bean:

要禁用自动配置的连接池指标,请设置以下属性:

To disable the auto-configured connection pool metrics, set the following property:

management:
  metrics:
    mongo:
      connectionpool:
        enabled: false

Jetty Metrics

自动配置使用 Micrometer 的 JettyServerThreadPoolMetrics 为 Jetty 的 ThreadPool 绑定指标。通过使用 Micrometer 的 JettyConnectionMetrics 绑定 Jetty 的 Connector 实例的指标,并在 configprop:server.ssl.enabled[] 设置为 true 时,绑定 Micrometer 的 JettySslHandshakeMetrics 指标。

Auto-configuration binds metrics for Jetty’s ThreadPool by using Micrometer’s JettyServerThreadPoolMetrics. Metrics for Jetty’s Connector instances are bound by using Micrometer’s JettyConnectionMetrics and, when configprop:server.ssl.enabled[] is set to true, Micrometer’s JettySslHandshakeMetrics.

@Timed Annotation Support

要启用 @Timed 注解的扫描,您需要将 configprop:management.observations.annotations.enabled[] 属性设置为 true 请参考 {url-micrometer-docs-concepts}#_the_timed_annotation[Micrometer 文档]。

To enable scanning of @Timed annotations, you will need to set the configprop:management.observations.annotations.enabled[] property to true. Please refer to the {url-micrometer-docs-concepts}#_the_timed_annotation[Micrometer documentation].

Redis Metrics

自动配置为自动配置的 LettuceConnectionFactory 注册一个 MicrometerCommandLatencyRecorder 有关更多详细信息,请参阅 Lettuce 文档的 {url-lettuce-docs}#command.latency.metrics.micrometer[Micrometer Metrics 部分]。

Auto-configuration registers a MicrometerCommandLatencyRecorder for the auto-configured LettuceConnectionFactory. For more detail, see the {url-lettuce-docs}#command.latency.metrics.micrometer[Micrometer Metrics section] of the Lettuce documentation.

Registering Custom Metrics

要注册自定义指标,将 MeterRegistry 注入到您的组件中:

To register custom metrics, inject MeterRegistry into your component:

如果您的指标依赖于其他 bean,我们建议您使用 MeterBinder 来注册它们:

If your metrics depend on other beans, we recommend that you use a MeterBinder to register them:

使用 MeterBinder 可确保设置正确的依赖关系,并且在检索指标值时该 bean 可用。如果您发现自己重复使用一系列指标在组件或应用程序之间进行检测,则 MeterBinder 实现也很有用。

Using a MeterBinder ensures that the correct dependency relationships are set up and that the bean is available when the metric’s value is retrieved. A MeterBinder implementation can also be useful if you find that you repeatedly instrument a suite of metrics across components or applications.

默认情况下,来自所有 MeterBinder bean 的指标都会自动绑定到 Spring 管理的 MeterRegistry 中。

By default, metrics from all MeterBinder beans are automatically bound to the Spring-managed MeterRegistry.

Customizing Individual Metrics

如果您需要对特定 Meter 实例应用自定义设置,则可以使用 io.micrometer.core.instrument.config.MeterFilter 接口。

If you need to apply customizations to specific Meter instances, you can use the io.micrometer.core.instrument.config.MeterFilter interface.

比如,如果你要对所有以 com.example 开头的指标 ID 将 mytag.region 标记重命名为 mytag.area,你可以执行以下操作:

For example, if you want to rename the mytag.region tag to mytag.area for all meter IDs beginning with com.example, you can do the following:

默认情况下,所有 MeterFilter bean 都是自动绑定到 Spring 管理的 MeterRegistry。请务必使用 Spring 管理的 MeterRegistry,而不是 Metrics 上的任何静态方法来注册你的指标。这些方法使用的是未由 Spring 管理的全局注册表。

By default, all MeterFilter beans are automatically bound to the Spring-managed MeterRegistry. Make sure to register your metrics by using the Spring-managed MeterRegistry and not any of the static methods on Metrics. These use the global registry that is not Spring-managed.

Common Tags

常见标记通常用于对操作环境进行维度向下钻取,比如主机、实例、地区、堆栈等等。常见标记对所有指标都适用,并且可以进行配置,如下面的示例所示:

Common tags are generally used for dimensional drill-down on the operating environment, such as host, instance, region, stack, and others. Commons tags are applied to all meters and can be configured, as the following example shows:

management:
  metrics:
    tags:
      region: "us-east-1"
      stack: "prod"

前一个示例向值分别为 us-east-1prod 的所有度量添加 regionstack 标记。

The preceding example adds region and stack tags to all meters with a value of us-east-1 and prod, respectively.

如果您使用 Graphite,常见标记的顺序很重要。由于此方法无法保证常见标记,因此建议 Graphite 用户改而定义自定义 MeterFilter

The order of common tags is important if you use Graphite. As the order of common tags cannot be guaranteed by using this approach, Graphite users are advised to define a custom MeterFilter instead.

Per-meter Properties

MeterFilter Bean 外,还可以使用属性对每个度量实施有限的自定义。使用 Spring Boot 的 PropertiesMeterFilter,可将每个度量自定义应用于以给定名称开头的任何度量 ID。以下示例将过滤掉任何 ID 以 example.remote 开头的度量。

In addition to MeterFilter beans, you can apply a limited set of customization on a per-meter basis using properties. Per-meter customizations are applied, using Spring Boot’s PropertiesMeterFilter, to any meter IDs that start with the given name. The following example filters out any meters that have an ID starting with example.remote.

management:
  metrics:
    enable:
      example:
        remote: false

以下属性允许按度量自定义:

The following properties allow per-meter customization:

Table 1. Per-meter customizations
Property Description

configprop:management.metrics.enable[]

Whether to accept meters with certain IDs. Meters that are not accepted are filtered from the MeterRegistry.

configprop:management.metrics.distribution.percentiles-histogram[]

Whether to publish a histogram suitable for computing aggregable (across dimension) percentile approximations.

configprop:management.metrics.distribution.minimum-expected-value[], configprop:management.metrics.distribution.maximum-expected-value[]

Publish fewer histogram buckets by clamping the range of expected values.

configprop:management.metrics.distribution.percentiles[]

Publish percentile values computed in your application

configprop:management.metrics.distribution.expiry[], configprop:management.metrics.distribution.buffer-length[]

Give greater weight to recent samples by accumulating them in ring buffers which rotate after a configurable expiry, with a configurable buffer length.

configprop:management.metrics.distribution.slo[]

Publish a cumulative histogram with buckets defined by your service-level objectives.

有关 percentiles-histogrampercentilesslo 背后概念的更多详细信息,请参阅 Micrometer 文档的{url-micrometer-docs-concepts}#_histograms_and_percentiles[“Histograms and percentiles” 部分]。

For more details on the concepts behind percentiles-histogram, percentiles, and slo, see the {url-micrometer-docs-concepts}#_histograms_and_percentiles[“Histograms and percentiles” section] of the Micrometer documentation.

Metrics Endpoint

Spring Boot 提供了一个 metrics 终端,您可以使用它诊断检查应用程序收集的指标。该终端默认不可用,必须公开它。请参阅 exposing endpoints 了解更多详细信息。

Spring Boot provides a metrics endpoint that you can use diagnostically to examine the metrics collected by an application. The endpoint is not available by default and must be exposed. See exposing endpoints for more details.

导航到 /actuator/metrics 会显示可用度量名称的列表。您可以通过将其名称作为选择器提供,来深入查看有关特定度量的详细信息,例如 /actuator/metrics/jvm.memory.max

Navigating to /actuator/metrics displays a list of available meter names. You can drill down to view information about a particular meter by providing its name as a selector — for example, /actuator/metrics/jvm.memory.max.

您在此处使用的名称应与代码中使用的名称匹配,而不是在将名称约定转换为它所配置的监控系统的名称。换句话说,如果 jvm.memory.max 由于其 snake case 命名约定而显示为 jvm_memory_max,则在 metrics 终端中检查度量时,您仍应使用 jvm.memory.max 作为选择器。

The name you use here should match the name used in the code, not the name after it has been naming-convention normalized for a monitoring system to which it is shipped. In other words, if jvm.memory.max appears as jvm_memory_max in Prometheus because of its snake case naming convention, you should still use jvm.memory.max as the selector when inspecting the meter in the metrics endpoint.

您还可以在 URL 末尾添加任意数量的 tag=KEY:VALUE 查询参数,以按维度向下深入查看,例如 /actuator/metrics/jvm.memory.max?tag=area:nonheap

You can also add any number of tag=KEY:VALUE query parameters to the end of the URL to dimensionally drill down on a meter — for example, /actuator/metrics/jvm.memory.max?tag=area:nonheap.

报告的测量值为与仪表名称和已应用的任何标签匹配的所有仪表的统计数据的“sum”。在前一个示例中,返回的“Value”统计数据是堆的““Code Cache””、““Compressed Class Space””和““Metaspace””区域的最大内存占用空间的总和。如果您仅希望查看““Metaspace””的最大大小,可以添加额外的“tag=id:Metaspace”(即“/actuator/metrics/jvm.memory.max?tag=area:nonheap&tag=id:Metaspace”)。

The reported measurements are the sum of the statistics of all meters that match the meter name and any tags that have been applied. In the preceding example, the returned Value statistic is the sum of the maximum memory footprints of the “Code Cache”, “Compressed Class Space”, and “Metaspace” areas of the heap. If you wanted to see only the maximum size for the “Metaspace”, you could add an additional tag=id:Metaspace — that is, /actuator/metrics/jvm.memory.max?tag=area:nonheap&tag=id:Metaspace.

Integration with Micrometer Observation

DefaultMeterObservationHandler”会在“ObservationRegistry”上自动注册,它会针对每个完成的观察值创建度量指标。

A DefaultMeterObservationHandler is automatically registered on the ObservationRegistry, which creates metrics for every completed observation.