Grafana dashboard: Java Metrics与Docker系统接口监控概览
Description: 微服务、Java Metrics、Docker、业务系统接口监控概览

微服务、Java Metrics、Docker、业务系统接口监控概览

1.记录类AccessMetricsFilter.java

@Log4j2
@Component
@ConditionalOnClass(MetricRegistry.class)
public class AccessMetricsFilter extends OncePerRequestFilter {
    private final String METRIC_SUFFIX_TIME = ".url_exec";

    @Value("${spring.application.name}")
    private String applicationName;

    private String[] excludeUrls = {};

    @Override
    public void afterPropertiesSet() throws ServletException {
        excludeUrls = new String[]{applicationName + "/tools/", applicationName + "/admin/tools"};
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        //排除url
        String sourceUrl = request.getRequestURI();
        for (String excludeUrl : excludeUrls) {
            if (sourceUrl.indexOf(excludeUrl) != -1) {
                return true;
            }
        }
        return false;
    }

    @Autowired
    private MetricRegistry metricRegistry;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI().replaceAll("[/\\.]", "_");
        long startTime = System.nanoTime();
        long duration = 0L;
        try {
            filterChain.doFilter(request, response);
            duration = System.nanoTime() - startTime;
        } finally {
            //优先取本次记录的错误码
            Integer statusCode = (Integer) request.getAttribute(Constants.SERVER_ERROR_CODE);
            if (statusCode == null) {
                statusCode = response.getStatus();
            }

            //记录分析数据
            Timer timer = metricRegistry.timer(uri + "." + statusCode + METRIC_SUFFIX_TIME);
            timer.update(duration, TimeUnit.NANOSECONDS);

            if (log.isInfoEnabled()) {
                log.info("req: url={}, time={}ms, status={}", uri, TimeUnit.MILLISECONDS.convert(duration, TimeUnit.NANOSECONDS), statusCode);
            }
        }
    }
}

2.指标上报配置类MetricsConfiguration.java
@Configuration
@ConditionalOnClass(MetricRegistry.class)
@EnableMetrics
@AutoConfigureAfter(MetricsConfig.class)
@Log4j2
public class MetricsConfiguration extends MetricsConfigurerAdapter {
    @Value("${spring.application.name}")
    private String applicationName;

    @Autowired
    private MetricsConfig metricsConfig;

    @Override
    public void configureReporters(MetricRegistry metricRegistry) {
        // 采集jvm指标
        metricRegistry.register("-.-.jvm.gc", new com.codahale.metrics.jvm.GarbageCollectorMetricSet());
        metricRegistry.register("-.-.jvm.memory", new com.codahale.metrics.jvm.MemoryUsageGaugeSet());
        metricRegistry.register("-.-.jvm.thread-states", new com.codahale.metrics.jvm.ThreadStatesGaugeSet());
        metricRegistry.register("-.-.jvm.fd.usage", new com.codahale.metrics.jvm.FileDescriptorRatioGauge());

        // 配置Influxdb
        HttpInfluxdbProtocol influxdbProtocol = new HttpInfluxdbProtocol("http", metricsConfig.getHost(), metricsConfig.getPort(), metricsConfig.getUsername(), metricsConfig.getPassword(), metricsConfig.getDb());
        InfluxdbReporter.Builder builder = InfluxdbReporter.forRegistry(metricRegistry).protocol(influxdbProtocol);
        builder.convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS);
        builder.filter(MetricFilter.ALL).skipIdleMetrics(true);
        builder.tag("server", applicationName).tag("ip", HttpUtil.getDockerHostIp()).tag("cid", HttpUtil.getLocalHostName());
        builder.transformer(new CategoriesMetricMeasurementTransformer("url", "code"));

        // 启动上报
        ScheduledReporter reporter = builder.build();
        reporter.start(metricsConfig.getPeriod(), TimeUnit.SECONDS);

        log.debug("grafana上报初始化完成：host={}, port={}, db={}", metricsConfig.getHost(), metricsConfig.getPort(), metricsConfig.getDb());
    }

}

{
  "__inputs": [
    {
      "name": "DS_7_79",
      "label": "default_db",
      "description": "默认数据库",
      "type": "datasource",
      "pluginId": "influxdb",
      "pluginName": "InfluxDB"
    }
  ],
  "__requires": [
    {
      "type": "grafana",
      "id": "grafana",
      "name": "Grafana",
      "version": "5.4.2"
    },
    {
      "type": "panel",
      "id": "grafana-piechart-panel",
      "name": "Pie Chart",
      "version": "1.3.6"
    },
    {
      "type": "panel",
      "id": "graph",
      "name": "Graph",
      "version": "5.0.0"
    },
    {
      "type": "datasource",
      "id": "influxdb",
      "name": "InfluxDB",
      "version": "5.0.0"
    },
    {
      "type": "panel",
      "id": "singlestat",
      "name": "Singlestat",
      "version": "5.0.0"
    }
  ],
  "annotations": {
    "list": [
      {
        "builtIn": 1,
        "datasource": "-- Grafana --",
        "enable": true,
        "hide": true,
        "iconColor": "rgba(0, 211, 255, 1)",
        "name": "Annotations & Alerts",
        "type": "dashboard"
      }
    ]
  },
  "editable": true,
  "gnetId": 10341,
  "graphTooltip": 0,
  "id": null,
  "iteration": 1560497950171,
  "links": [],
  "panels": [
    {
      "collapsed": false,
      "gridPos": {
        "h": 1,
        "w": 24,
        "x": 0,
        "y": 0
      },
      "id": 18,
      "panels": [],
      "title": "概览",
      "type": "row"
    },
    {
      "cacheTimeout": null,
      "colorBackground": false,
      "colorValue": true,
      "colors": [
        "#299c46",
        "#eab839",
        "#d44a3a"
      ],
      "datasource": "${DS_7_79}",
      "format": "locale",
      "gauge": {
        "maxValue": 100,
        "minValue": 0,
        "show": false,
        "thresholdLabels": false,
        "thresholdMarkers": true
      },
      "gridPos": {
        "h": 6,
        "w": 6,
        "x": 0,
        "y": 1
      },
      "id": 26,
      "interval": null,
      "links": [],
      "mappingType": 1,
      "mappingTypes": [
        {
          "name": "value to text",
          "value": 1
        },
        {
          "name": "range to text",
          "value": 2
        }
      ],
      "maxDataPoints": 100,
      "nullPointMode": "connected",
      "nullText": null,
      "postfix": "",
      "postfixFontSize": "50%",
      "prefix": "",
      "prefixFontSize": "50%",
      "rangeMaps": [
        {
          "from": "null",
          "text": "N/A",
          "to": "null"
        }
      ],
      "sparkline": {
        "fillColor": "rgba(31, 118, 189, 0.18)",
        "full": false,
        "lineColor": "rgb(31, 120, 193)",
        "show": false
      },
      "tableColumn": "",
      "targets": [
        {
          "groupBy": [],
          "hide": false,
          "measurement": "url_exec",
          "orderByTime": "ASC",
          "policy": "default",
          "query": "select sum(\"spread\") from( SELECT SPREAD(\"run-count\") FROM \"url_exec\" where $timeFilter  group by \"server\",\"cid\",\"url\",\"code\")",
          "rawQuery": true,
          "refId": "A",
          "resultFormat": "time_series",
          "select": [
            [
              {
                "params": [
                  "run-count"
                ],
                "type": "field"
              },
              {
                "params": [],
                "type": "max"
              }
            ]
          ],
          "tags": [
            {
              "key": "server",
              "operator": "=~",
              "value": "/^$server$/"
            }
          ]
        }
      ],
      "thresholds": "",
      "title": "总请求量",
      "transparent": true,
      "type": "singlestat",
      "valueFontSize": "80%",
      "valueMaps": [
        {
          "op": "=",
          "text": "N/A",
          "value": "null"
        }
      ],
      "valueName": "avg"
    },
    {
      "aliasColors": {},
      "breakPoint": "50%",
      "cacheTimeout": null,
      "combine": {
        "label": "Others",
        "threshold": 0
      },
      "datasource": "${DS_7_79}",
      "decimals": null,
      "fontSize": "50%",
      "format": "locale",
      "gridPos": {
        "h": 6,
        "w": 8,
        "x": 6,
        "y": 1
      },
      "id": 22,
      "interval": null,
      "legend": {
        "header": "",
        "percentage": true,
        "percentageDecimals": null,
        "show": true,
        "sort": "current",
        "sortDesc": true,
        "values": true
      },
      "legendType": "Right side",
      "links": [],
      "maxDataPoints": 3,
      "nullPointMode": "connected",
      "pieType": "pie",
      "strokeWidth": 1,
      "targets": [
        {
          "alias": "$tag_server",
          "groupBy": [
            {
              "params": [
                "server"
              ],
              "type": "tag"
            }
          ],
          "hide": false,
          "measurement": "url_exec",
          "orderByTime": "ASC",
          "policy": "default",
          "query": "select sum(\"spread\") from ( SELECT SPREAD(\"run-count\") FROM \"url_exec\" where $timeFilter group by \"server\",\"cid\",\"url\" ,\"code\") group by \"server\"",
          "rawQuery": true,
          "refId": "A",
          "resultFormat": "time_series",
          "select": [
            [
              {
                "params": [
                  "run-count"
                ],
                "type": "field"
              }
            ]
          ],
          "tags": []
        }
      ],
      "title": "业务请求量",
      "transparent": true,
      "type": "grafana-piechart-panel",
      "valueName": "current"
    },
    {
      "aliasColors": {},
      "breakPoint": "50%",
      "cacheTimeout": null,
      "combine": {
        "label": "Others",
        "threshold": 0
      },
      "datasource": "${DS_7_79}",
      "fontSize": "80%",
      "format": "short",
      "gridPos": {
        "h": 6,
        "w": 8,
        "x": 14,
        "y": 1
      },
      "id": 24,
      "interval": null,
      "legend": {
        "percentage": true,
        "show": true,
        "values": true
      },
      "legendType": "Right side",
      "links": [],
      "maxDataPoints": 3,
      "nullPointMode": "connected",
      "pieType": "pie",
      "strokeWidth": 1,
      "targets": [
        {
          "alias": "$tag_code",
          "groupBy": [
            {
              "params": [
                "$__interval"
              ],
              "type": "time"
            },
            {
              "params": [
                "code"
              ],
              "type": "tag"
            },
            {
              "params": [
                "null"
              ],
              "type": "fill"
            }
          ],
          "hide": false,
          "measurement": "url_err",
          "orderByTime": "ASC",
          "policy": "default",
          "query": "select sum(\"spread\") from( SELECT spread(\"run-count\") FROM \"url_exec\" WHERE $timeFilter and code != '200' AND \"cid\" =~ /^[^\\s]+$/ GROUP BY  \"server\", \"cid\",\"url\",\"code\") group by \"code\"",
          "rawQuery": true,
          "refId": "A",
          "resultFormat": "time_series",
          "select": [
            [
              {
                "params": [
                  "count"
                ],
                "type": "field"
              },
              {
                "params": [],
                "type": "sum"
              }
            ]
          ],
          "tags": []
        }
      ],
      "title": "错误数分布",
      "transparent": true,
      "type": "grafana-piechart-panel",
      "valueName": "current"
    },
    {
      "collapsed": false,
      "gridPos": {
        "h": 1,
        "w": 24,
        "x": 0,
        "y": 7
      },
      "id": 11,
      "panels": [],
      "title": "接口概览",
      "type": "row"
    },
    {
      "aliasColors": {},
      "bars": false,
      "dashLength": 10,
      "dashes": false,
      "datasource": "${DS_7_79}",
      "fill": 1,
      "gridPos": {
        "h": 7,
        "w": 12,
        "x": 0,
        "y": 8
      },
      "id": 9,
      "legend": {
        "alignAsTable": true,
        "avg": true,
        "current": true,
        "max": true,
        "min": true,
        "rightSide": true,
        "show": true,
        "sort": "avg",
        "sortDesc": true,
        "total": false,
        "values": true
      },
      "lines": true,
      "linewidth": 1,
      "links": [],
      "nullPointMode": "null",
      "percentage": false,
      "pointradius": 5,
      "points": false,
      "renderer": "flot",
      "seriesOverrides": [],
      "spaceLength": 10,
      "stack": false,
      "steppedLine": false,
      "targets": [
        {
          "alias": "$tag_server",
          "groupBy": [
            {
              "params": [
                "$__interval"
              ],
              "type": "time"
            },
            {
              "params": [
                "server"
              ],
              "type": "tag"
            },
            {
              "params": [
                "null"
              ],
              "type": "fill"
            }
          ],
          "hide": false,
          "measurement": "url_exec",
          "orderByTime": "ASC",
          "policy": "default",
          "query": "select sum(\"mean\") from(  SELECT mean(\"one-minute\") FROM \"url_exec\" WHERE $timeFilter AND \"cid\" =~ /^[^\\s]+$/ GROUP BY  \"server\",\"cid\",\"url\",\"code\" ) group by time($TimeGranularity), \"server\"",
          "rawQuery": true,
          "refId": "A",
          "resultFormat": "time_series",
          "select": [
            [
              {
                "params": [
                  "one-minute"
                ],
                "type": "field"
              },
              {
                "params": [],
                "type": "mean"
              }
            ]
          ],
          "tags": []
        }
      ],
      "thresholds": [],
      "timeFrom": null,
      "timeRegions": [],
      "timeShift": null,
      "title": "RPS",
      "tooltip": {
        "shared": true,
        "sort": 0,
        "value_type": "individual"
      },
      "type": "graph",
      "xaxis": {
        "buckets": null,
        "mode": "time",
        "name": null,
        "show": true,
        "values": []
      },
      "yaxes": [
        {
          "format": "short",
          "label": "",
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        },
        {
          "format": "short",
          "label": "",
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        }
      ],
      "yaxis": {
        "align": false,
        "alignLevel": null
      }
    },
    {
      "aliasColors": {},
      "bars": false,
      "dashLength": 10,
      "dashes": false,
      "datasource": "${DS_7_79}",
      "fill": 1,
      "gridPos": {
        "h": 7,
        "w": 12,
        "x": 12,
        "y": 8
      },
      "id": 16,
      "legend": {
        "alignAsTable": true,
        "avg": true,
        "current": true,
        "max": true,
        "min": true,
        "rightSide": true,
        "show": true,
        "sort": "avg",
        "sortDesc": true,
        "total": false,
        "values": true
      },
      "lines": true,
      "linewidth": 1,
      "links": [],
      "nullPointMode": "null",
      "percentage": false,
      "pointradius": 5,
      "points": false,
      "renderer": "flot",
      "seriesOverrides": [],
      "spaceLength": 10,
      "stack": false,
      "steppedLine": false,
      "targets": [
        {
          "alias": "$tag_server",
          "groupBy": [
            {
              "params": [
                "$__interval"
              ],
              "type": "time"
            },
            {
              "params": [
                "server"
              ],
              "type": "tag"
            },
            {
              "params": [
                "null"
              ],
              "type": "fill"
            }
          ],
          "hide": false,
          "measurement": "url_exec",
          "orderByTime": "ASC",
          "policy": "default",
          "query": "SELECT mean(\"mean\") FROM \"url_exec\" WHERE $timeFilter AND \"cid\" =~ /^[^\\s]+$/ GROUP BY time($TimeGranularity), \"server\" fill(null)",
          "rawQuery": true,
          "refId": "A",
          "resultFormat": "time_series",
          "select": [
            [
              {
                "params": [
                  "mean"
                ],
                "type": "field"
              },
              {
                "params": [],
                "type": "mean"
              }
            ]
          ],
          "tags": []
        }
      ],
      "thresholds": [],
      "timeFrom": null,
      "timeRegions": [],
      "timeShift": null,
      "title": "RT",
      "tooltip": {
        "shared": true,
        "sort": 0,
        "value_type": "individual"
      },
      "type": "graph",
      "xaxis": {
        "buckets": null,
        "mode": "time",
        "name": null,
        "show": true,
        "values": []
      },
      "yaxes": [
        {
          "format": "ms",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        },
        {
          "format": "short",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        }
      ],
      "yaxis": {
        "align": false,
        "alignLevel": null
      }
    },
    {
      "aliasColors": {},
      "bars": false,
      "dashLength": 10,
      "dashes": false,
      "fill": 1,
      "gridPos": {
        "h": 7,
        "w": 12,
        "x": 0,
        "y": 15
      },
      "hideTimeOverride": false,
      "id": 28,
      "legend": {
        "alignAsTable": true,
        "avg": true,
        "current": false,
        "max": true,
        "min": true,
        "rightSide": true,
        "show": true,
        "sort": "avg",
        "sortDesc": true,
        "total": false,
        "values": true
      },
      "lines": true,
      "linewidth": 1,
      "links": [],
      "nullPointMode": "null",
      "percentage": false,
      "pointradius": 5,
      "points": false,
      "renderer": "flot",
      "seriesOverrides": [],
      "spaceLength": 10,
      "stack": false,
      "steppedLine": false,
      "targets": [
        {
          "alias": "$tag_server",
          "groupBy": [
            {
              "params": [
                "$__interval"
              ],
              "type": "time"
            },
            {
              "params": [
                "null"
              ],
              "type": "fill"
            }
          ],
          "hide": false,
          "orderByTime": "ASC",
          "policy": "default",
          "query": "select sum(\"mean\") from(  SELECT mean(\"one-minute\") FROM \"url_exec\" WHERE $timeFilter GROUP BY  \"server\",\"cid\",\"url\",\"code\" ) group by time($TimeGranularity), \"server\"",
          "rawQuery": true,
          "refId": "A",
          "resultFormat": "time_series",
          "select": [
            [
              {
                "params": [
                  "value"
                ],
                "type": "field"
              },
              {
                "params": [],
                "type": "mean"
              }
            ]
          ],
          "tags": []
        }
      ],
      "thresholds": [],
      "timeFrom": null,
      "timeRegions": [],
      "timeShift": "1d",
      "title": "RPS-昨日同期",
      "tooltip": {
        "shared": true,
        "sort": 0,
        "value_type": "individual"
      },
      "type": "graph",
      "xaxis": {
        "buckets": null,
        "mode": "time",
        "name": null,
        "show": true,
        "values": []
      },
      "yaxes": [
        {
          "format": "short",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        },
        {
          "format": "short",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        }
      ],
      "yaxis": {
        "align": false,
        "alignLevel": null
      }
    },
    {
      "aliasColors": {},
      "bars": false,
      "dashLength": 10,
      "dashes": false,
      "fill": 1,
      "gridPos": {
        "h": 7,
        "w": 12,
        "x": 12,
        "y": 15
      },
      "id": 30,
      "legend": {
        "alignAsTable": true,
        "avg": true,
        "current": false,
        "max": true,
        "min": true,
        "rightSide": true,
        "show": true,
        "sort": "avg",
        "sortDesc": true,
        "total": false,
        "values": true
      },
      "lines": true,
      "linewidth": 1,
      "links": [],
      "nullPointMode": "null",
      "percentage": false,
      "pointradius": 5,
      "points": false,
      "renderer": "flot",
      "seriesOverrides": [],
      "spaceLength": 10,
      "stack": false,
      "steppedLine": false,
      "targets": [
        {
          "alias": "$tag_server",
          "groupBy": [
            {
              "params": [
                "$__interval"
              ],
              "type": "time"
            },
            {
              "params": [
                "null"
              ],
              "type": "fill"
            }
          ],
          "orderByTime": "ASC",
          "policy": "default",
          "query": "SELECT mean(\"mean\") FROM \"url_exec\" WHERE $timeFilter GROUP BY time($TimeGranularity), \"server\" fill(null)",
          "rawQuery": true,
          "refId": "A",
          "resultFormat": "time_series",
          "select": [
            [
              {
                "params": [
                  "value"
                ],
                "type": "field"
              },
              {
                "params": [],
                "type": "mean"
              }
            ]
          ],
          "tags": []
        }
      ],
      "thresholds": [],
      "timeFrom": null,
      "timeRegions": [],
      "timeShift": "1d",
      "title": "RT-昨日同期",
      "tooltip": {
        "shared": true,
        "sort": 0,
        "value_type": "individual"
      },
      "type": "graph",
      "xaxis": {
        "buckets": null,
        "mode": "time",
        "name": null,
        "show": true,
        "values": []
      },
      "yaxes": [
        {
          "format": "ms",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        },
        {
          "format": "short",
          "label": null,
          "logBase": 1,
          "max": null,
          "min": null,
          "show": true
        }
      ],
      "yaxis": {
        "align": false,
        "alignLevel": null
      }
    }
  ],
  "refresh": false,
  "schemaVersion": 16,
  "style": "dark",
  "tags": [],
  "templating": {
    "list": [
      {
        "allValue": null,
        "current": {
          "selected": false,
          "text": "1m",
          "value": "1m"
        },
        "hide": 0,
        "includeAll": false,
        "label": null,
        "multi": false,
        "name": "TimeGranularity",
        "options": [
          {
            "selected": false,
            "text": "1s",
            "value": "1s"
          },
          {
            "selected": false,
            "text": "5s",
            "value": "5s"
          },
          {
            "selected": false,
            "text": "10s",
            "value": "10s"
          },
          {
            "selected": false,
            "text": "30s",
            "value": "30s"
          },
          {
            "selected": true,
            "text": "1m",
            "value": "1m"
          },
          {
            "selected": false,
            "text": "2m",
            "value": "2m"
          },
          {
            "selected": false,
            "text": "5m",
            "value": "5m"
          },
          {
            "selected": false,
            "text": "10m",
            "value": "10m"
          },
          {
            "selected": false,
            "text": "30m",
            "value": "30m"
          }
        ],
        "query": "1s,5s,10s,30s,1m,2m,5m,10m,30m",
        "skipUrlSync": false,
        "type": "custom"
      }
    ]
  },
  "time": {
    "from": "now-5m",
    "to": "now"
  },
  "timepicker": {
    "refresh_intervals": [
      "5s",
      "10s",
      "30s",
      "1m",
      "5m",
      "15m",
      "30m",
      "1h",
      "2h",
      "1d"
    ],
    "time_options": [
      "5m",
      "15m",
      "1h",
      "6h",
      "12h",
      "24h",
      "2d",
      "7d",
      "30d"
    ]
  },
  "timezone": "",
  "title": "Java Metrics与Docker系统接口监控概览",
  "uid": "c2Hs41MWx",
  "version": 70,
  "description": "微服务、Java Metrics、Docker、业务系统接口监控概览"
}