dashboarding

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Grafana Dashboard Authoring

Grafana 仪表盘制作

Dashboards are JSON documents stored in Grafana. Every dashboard has panels, variables, time range, and refresh settings. Understanding the JSON schema lets you programmatically create and modify dashboards via the API or Grafana Assistant tools.

Grafana中的仪表盘是以JSON文档形式存储的。每个仪表盘都包含面板、变量、时间范围和刷新设置。了解JSON架构后,你可以通过API或Grafana辅助工具以编程方式创建和修改仪表盘。

Dashboard JSON structure

仪表盘JSON结构

json
{
  "title": "My Dashboard",
  "uid": "my-dashboard-v1",
  "tags": ["service", "production"],
  "time": { "from": "now-1h", "to": "now" },
  "refresh": "30s",
  "timezone": "browser",
  "schemaVersion": 41,
  "templating": { "list": [] },
  "annotations": { "list": [] },
  "panels": []
}
Key fields:
  • uid
    - stable identifier used in URLs and API calls; keep it short and meaningful
  • schemaVersion
    - use
    41
    for Grafana 11+
  • time.from
    /
    to
    - supports relative (
    now-1h
    ,
    now-7d
    ) and absolute ISO timestamps
  • refresh
    - auto-refresh interval (
    "30s"
    ,
    "1m"
    ,
    "5m"
    ,
    ""
    for off)

json
{
  "title": "My Dashboard",
  "uid": "my-dashboard-v1",
  "tags": ["service", "production"],
  "time": { "from": "now-1h", "to": "now" },
  "refresh": "30s",
  "timezone": "browser",
  "schemaVersion": 41,
  "templating": { "list": [] },
  "annotations": { "list": [] },
  "panels": []
}
核心字段说明:
  • uid
    - 用于URL和API调用的稳定标识符;建议简短且有意义
  • schemaVersion
    - Grafana 11+版本请使用
    41
  • time.from
    /
    to
    - 支持相对时间(
    now-1h
    now-7d
    )和绝对ISO时间戳
  • refresh
    - 自动刷新间隔(
    "30s"
    "1m"
    "5m"
    ,空字符串表示关闭)

Panel types and when to use them

面板类型及适用场景

PanelUse case
Time seriesAny metric over time; the default choice for counters, rates, gauges
StatSingle current value with optional sparkline (e.g. uptime, current RPS)
GaugePercent or value against a min/max (e.g. disk usage %)
Bar gaugeCompare multiple values side by side (e.g. top 10 services by RPS)
TableMulti-column data (e.g. alert list with labels)
HeatmapDistribution over time (e.g. request duration histogram)
LogsLoki log streams
TracesTempo trace search
TextMarkdown documentation panels
CandlestickOHLC/financial data (or min/max/avg patterns)
Node graphService dependency graphs

面板类型适用场景
Time series(时间序列)随时间变化的任意指标;是计数器、速率、仪表盘类指标的默认选择
Stat(统计)单个当前值,可搭配迷你折线图(如在线时长、当前请求每秒数RPS)
Gauge(仪表盘)百分比或相对最小/最大值的数值(如磁盘使用率%)
Bar gauge(条形仪表盘)并列对比多个数值(如按RPS排名的前10个服务)
Table(表格)多列数据(如带标签的告警列表)
Heatmap(热力图)随时间分布的数据(如请求时长直方图)
Logs(日志)Loki日志流
Traces(链路追踪)Tempo链路搜索
Text(文本)Markdown文档面板
Candlestick(K线图)OHLC/金融数据(或最小/最大/平均值模式)
Node graph(节点图)服务依赖关系图

Panel JSON structure

面板JSON结构

json
{
  "id": 1,
  "type": "timeseries",
  "title": "Request Rate",
  "gridPos": { "x": 0, "y": 0, "w": 12, "h": 8 },
  "datasource": { "type": "prometheus", "uid": "${datasource}" },
  "targets": [
    {
      "expr": "sum(rate(http_requests_total{job=\"$job\"}[5m])) by (status_code)",
      "legendFormat": "{{status_code}}",
      "refId": "A"
    }
  ],
  "fieldConfig": {
    "defaults": {
      "unit": "reqps",
      "thresholds": {
        "mode": "absolute",
        "steps": [
          { "color": "green", "value": null },
          { "color": "yellow", "value": 1000 },
          { "color": "red", "value": 5000 }
        ]
      }
    },
    "overrides": []
  },
  "options": {
    "legend": { "calcs": ["mean", "max", "last"], "displayMode": "table", "placement": "bottom" },
    "tooltip": { "mode": "multi", "sort": "desc" }
  }
}
gridPos
:
The dashboard uses a 24-column grid. Common widths: full-width=24, half=12, third=8, quarter=6. Height in grid units (1 unit ≈ 30px).

json
{
  "id": 1,
  "type": "timeseries",
  "title": "Request Rate",
  "gridPos": { "x": 0, "y": 0, "w": 12, "h": 8 },
  "datasource": { "type": "prometheus", "uid": "${datasource}" },
  "targets": [
    {
      "expr": "sum(rate(http_requests_total{job=\"$job\"}[5m])) by (status_code)",
      "legendFormat": "{{status_code}}",
      "refId": "A"
    }
  ],
  "fieldConfig": {
    "defaults": {
      "unit": "reqps",
      "thresholds": {
        "mode": "absolute",
        "steps": [
          { "color": "green", "value": null },
          { "color": "yellow", "value": 1000 },
          { "color": "red", "value": 5000 }
        ]
      }
    },
    "overrides": []
  },
  "options": {
    "legend": { "calcs": ["mean", "max", "last"], "displayMode": "table", "placement": "bottom" },
    "tooltip": { "mode": "multi", "sort": "desc" }
  }
}
gridPos
仪表盘采用24列网格布局。常见宽度:全屏=24、半屏=12、三分之一屏=8、四分之一屏=6。高度以网格单位计算(1单位≈30px)。

Useful unit identifiers

常用单位标识符

undefined
undefined

Rates

速率

"reqps" -- requests per second "ops" -- operations per second "Bps" -- bytes per second "percentunit" -- 0.0-1.0 as percentage
"reqps" -- 请求每秒 "ops" -- 操作每秒 "Bps" -- 字节每秒 "percentunit" -- 0.0-1.0 转换为百分比

Storage

存储

"bytes" -- bytes (auto-scales to KB/MB/GB) "decbytes" -- decimal bytes (1 KB = 1000 B)
"bytes" -- 字节(自动转换为KB/MB/GB) "decbytes" -- 十进制字节(1 KB = 1000 B)

Time

时间

"ms" -- milliseconds "s" -- seconds "dtdurationms" -- duration in ms (shows as "1h 2m 3s")
"ms" -- 毫秒 "s" -- 秒 "dtdurationms" -- 毫秒级时长(显示为"1h 2m 3s")

Counts

计数

"short" -- compact number (1.2k, 3.4M) "none" -- raw number

Full list: **Panel > Field > Unit** dropdown in Grafana UI, or the [units reference](https://grafana.com/docs/grafana/latest/panels-visualizations/configure-standard-options/#unit).

---
"short" -- 紧凑数字格式(1.2k、3.4M) "none" -- 原始数字

完整列表:可在Grafana界面的**面板 > 字段 > 单位**下拉菜单中查看,或参考[官方单位文档](https://grafana.com/docs/grafana/latest/panels-visualizations/configure-standard-options/#unit)。

---

Template variables

模板变量

Variables make dashboards reusable across environments and services.
Query variable (populates from metric labels):
json
{
  "name": "job",
  "type": "query",
  "datasource": { "type": "prometheus", "uid": "prometheus" },
  "query": { "query": "label_values(up, job)", "refId": "A" },
  "refresh": 2,
  "includeAll": true,
  "multi": true,
  "label": "Service"
}
Constant variable:
json
{
  "name": "cluster",
  "type": "constant",
  "query": "production",
  "label": "Cluster"
}
Datasource variable (switch data sources without editing queries):
json
{
  "name": "datasource",
  "type": "datasource",
  "pluginId": "prometheus",
  "includeAll": false,
  "label": "Prometheus"
}
Use variables in queries:
promql
undefined
变量可让仪表盘在不同环境和服务间复用。
查询变量(从指标标签中获取值):
json
{
  "name": "job",
  "type": "query",
  "datasource": { "type": "prometheus", "uid": "prometheus" },
  "query": { "query": "label_values(up, job)", "refId": "A" },
  "refresh": 2,
  "includeAll": true,
  "multi": true,
  "label": "Service"
}
常量变量:
json
{
  "name": "cluster",
  "type": "constant",
  "query": "production",
  "label": "Cluster"
}
数据源变量(无需修改查询即可切换数据源):
json
{
  "name": "datasource",
  "type": "datasource",
  "pluginId": "prometheus",
  "includeAll": false,
  "label": "Prometheus"
}
在查询中使用变量:
promql
undefined

Reference a variable in a PromQL query

在PromQL查询中引用变量

rate(http_requests_total{job=~"$job"}[5m])
rate(http_requests_total{job=~"$job"}[5m])

Multi-value variable uses regex OR automatically

多值变量会自动转换为正则或逻辑

When $job = ["api", "worker"], it becomes job=~"api|worker"

当$job = ["api", "worker"]时,会自动变为job=~"api|worker"


**Chain variables** (second variable filters based on first):

```json
{
  "name": "pod",
  "query": "label_values(kube_pod_info{namespace=\"$namespace\"}, pod)"
}


**链式变量**(第二个变量基于第一个变量过滤):

```json
{
  "name": "pod",
  "query": "label_values(kube_pod_info{namespace=\"$namespace\"}, pod)"
}

Transformations

数据转换

Transformations run client-side after data is fetched, reshaping results without changing queries.
Common transformations:
json
"transformations": [
  {
    "id": "merge",
    "options": {}
  },
  {
    "id": "organize",
    "options": {
      "renameByName": { "Value #A": "Request Rate", "Value #B": "Error Rate" },
      "excludeByName": { "Time": true }
    }
  },
  {
    "id": "calculateField",
    "options": {
      "alias": "Error %",
      "mode": "reduceRow",
      "reduce": { "reducer": "last" },
      "binary": {
        "left": "errors",
        "right": "total",
        "operator": "/"
      }
    }
  },
  {
    "id": "filterByValue",
    "options": {
      "filters": [{ "fieldName": "Error %", "config": { "id": "greater", "options": { "value": 0.01 } } }],
      "type": "include",
      "match": "any"
    }
  }
]
Key transformation IDs:
merge
,
organize
,
rename
,
calculateField
,
filterByValue
,
groupBy
,
sortBy
,
limit
,
labelsToFields
,
seriesToRows
,
partitionByValues
.

数据转换在客户端获取数据后执行,无需修改查询即可重塑结果。
常见转换示例:
json
"transformations": [
  {
    "id": "merge",
    "options": {}
  },
  {
    "id": "organize",
    "options": {
      "renameByName": { "Value #A": "Request Rate", "Value #B": "Error Rate" },
      "excludeByName": { "Time": true }
    }
  },
  {
    "id": "calculateField",
    "options": {
      "alias": "Error %",
      "mode": "reduceRow",
      "reduce": { "reducer": "last" },
      "binary": {
        "left": "errors",
        "right": "total",
        "operator": "/"
      }
    }
  },
  {
    "id": "filterByValue",
    "options": {
      "filters": [{ "fieldName": "Error %", "config": { "id": "greater", "options": { "value": 0.01 } } }],
      "type": "include",
      "match": "any"
    }
  }
]
核心转换ID:
merge
organize
rename
calculateField
filterByValue
groupBy
sortBy
limit
labelsToFields
seriesToRows
partitionByValues

Dashboard linking

仪表盘链接

Panel link (click a panel to go somewhere):
json
"links": [
  {
    "title": "Go to details",
    "url": "/d/details-dashboard?var-service=${__field.labels.service}",
    "targetBlank": false
  }
]
Dashboard link (top-right corner links):
json
"links": [
  {
    "title": "Runbook",
    "url": "https://wiki.example.com/runbook/${job}",
    "icon": "external link",
    "targetBlank": true,
    "type": "link"
  }
]
Built-in variables for links:
  • ${__value.raw}
    - current data point value
  • ${__field.labels.job}
    - label value from current series
  • ${__url.params}
    - current URL query parameters (pass-through)
  • ${__from}
    /
    ${__to}
    - current time range as Unix ms

面板链接(点击面板跳转至指定位置):
json
"links": [
  {
    "title": "查看详情",
    "url": "/d/details-dashboard?var-service=${__field.labels.service}",
    "targetBlank": false
  }
]
仪表盘链接(右上角导航链接):
json
"links": [
  {
    "title": "运行手册",
    "url": "https://wiki.example.com/runbook/${job}",
    "icon": "external link",
    "targetBlank": true,
    "type": "link"
  }
]
链接内置变量:
  • ${__value.raw}
    - 当前数据点的原始值
  • ${__field.labels.job}
    - 当前序列的标签值
  • ${__url.params}
    - 当前URL的查询参数(透传)
  • ${__from}
    /
    ${__to}
    - 当前时间范围的毫秒级时间戳

Annotations

注释功能

Show events overlaid on time series panels (deployments, incidents, etc.).
Query annotation from Loki:
json
{
  "datasource": { "type": "loki", "uid": "loki" },
  "expr": "{job=\"deployments\"} |= \"deployed\"",
  "name": "Deployments",
  "iconColor": "blue",
  "titleFormat": "{{service}} deployed",
  "textFormat": "{{version}} by {{author}}"
}
Query annotation from Prometheus:
json
{
  "datasource": { "type": "prometheus", "uid": "prometheus" },
  "expr": "changes(kube_deployment_status_observed_generation{namespace=\"production\"}[5m]) > 0",
  "step": "60s",
  "name": "Deployments",
  "iconColor": "blue",
  "titleFormat": "Deploy: {{deployment}}"
}

在时间序列面板上叠加显示事件(如部署、故障等)。
从Loki查询注释:
json
{
  "datasource": { "type": "loki", "uid": "loki" },
  "expr": "{job=\"deployments\"} |= \"deployed\"",
  "name": "部署记录",
  "iconColor": "blue",
  "titleFormat": "{{service}} 已部署",
  "textFormat": "版本:{{version}},部署人:{{author}}"
}
从Prometheus查询注释:
json
{
  "datasource": { "type": "prometheus", "uid": "prometheus" },
  "expr": "changes(kube_deployment_status_observed_generation{namespace=\"production\"}[5m]) > 0",
  "step": "60s",
  "name": "部署记录",
  "iconColor": "blue",
  "titleFormat": "部署:{{deployment}}"
}

Dashboard via API

通过API操作仪表盘

bash
undefined
bash
undefined

Create or update a dashboard

创建或更新仪表盘

curl -s -X POST
-H "Authorization: Bearer <API_KEY>"
-H "Content-Type: application/json"
"https://myorg.grafana.net/api/dashboards/db"
-d '{ "dashboard": { <dashboard JSON> }, "folderUid": "my-folder", "overwrite": true, "message": "Updated via API" }'
curl -s -X POST
-H "Authorization: Bearer <API_KEY>"
-H "Content-Type: application/json"
"https://myorg.grafana.net/api/dashboards/db"
-d '{ "dashboard": { <dashboard JSON> }, "folderUid": "my-folder", "overwrite": true, "message": "Updated via API" }'

Get a dashboard by UID

通过UID获取仪表盘

curl -s -H "Authorization: Bearer <API_KEY>"
"https://myorg.grafana.net/api/dashboards/uid/my-dashboard-v1" | jq '.dashboard'
curl -s -H "Authorization: Bearer <API_KEY>"
"https://myorg.grafana.net/api/dashboards/uid/my-dashboard-v1" | jq '.dashboard'

Search dashboards

搜索仪表盘

curl -s -H "Authorization: Bearer <API_KEY>"
"https://myorg.grafana.net/api/search?query=kubernetes&type=dash-db" |
jq '.[] | {uid, title, folderTitle}'
curl -s -H "Authorization: Bearer <API_KEY>"
"https://myorg.grafana.net/api/search?query=kubernetes&type=dash-db" |
jq '.[] | {uid, title, folderTitle}'

Create a folder

创建文件夹

curl -s -X POST
-H "Authorization: Bearer <API_KEY>"
-H "Content-Type: application/json"
"https://myorg.grafana.net/api/folders"
-d '{"uid": "platform-team", "title": "Platform Team"}'

---
curl -s -X POST
-H "Authorization: Bearer <API_KEY>"
-H "Content-Type: application/json"
"https://myorg.grafana.net/api/folders"
-d '{"uid": "platform-team", "title": "Platform Team"}'

---

Grafana scenes (app plugins)

Grafana Scenes(应用插件)

For dashboards embedded in app plugins, use
@grafana/scenes
instead of raw JSON. See the
grafana-o11y:grafana-scenes
skill for the React-based scenes API.

对于嵌入在应用插件中的仪表盘,请使用
@grafana/scenes
而非原始JSON。关于基于React的Scenes API,请参考
grafana-o11y:grafana-scenes
技能文档。

References

参考文档