Skip to main content

Integrating with Grafana

1. Adding Prometheus Data Source

Example: Add Prometheus as a data source in Grafana

datasources:
  - name: Prometheus
    type: prometheus
    uid: prometheus-ds
    access: proxy
    url: http://localhost:9090
    isDefault: true
    editable: false
Field Description Notes
name Name of the data source Must be unique within Grafana
type Type of data source Must be prometheus
uid Unique identifier for the data source Used internally by Grafana
access Access mode for the data source proxy or direct
url URL of the Prometheus server Must be accessible from Grafana
isDefault Set as default data source Boolean value
editable Allow editing in the UI Boolean value
Note: Ensure that the Prometheus server is accessible from Grafana and that the URL is correctly configured.

2. Configuring Authentication

Option Values Notes
auth.type basic, jwt, oauth2 Authentication method to use
auth.basic.username admin Username for basic auth
auth.basic.password secret Password for basic auth
auth.jwt.secret jwt_secret_key Secret key for JWT signing
auth.oauth2.client_id grafana_client_id OAuth2 client ID for Grafana
auth.oauth2.client_secret grafana_client_secret OAuth2 client secret for Grafana

Example: Basic Authentication Configuration

auth:
  type: basic
  basic:
    username: admin
    password: secret

Example: JWT Authentication Configuration

auth:
  type: jwt
  jwt:
    secret: jwt_secret_key

Example: OAuth2 Authentication Configuration

auth:
  type: oauth2
  oauth2:
    client_id: grafana_client_id
    client_secret: grafana_client_secret

3. Using PromQL in Grafana

Example: Basic Query in Grafana

up
Expression Description Notes
up Boolean indicator if a target is healthy Returns 1 for up, 0 for down
rate(http_requests_total[5m]) Rate of HTTP requests over last 5 minutes Useful for calculating request rates
count by (job) (up) Count of up/down targets by job Grouping for aggregation
Note: Grafana supports PromQL natively in its query editor. Queries can be visualized directly in dashboards.

Example: Aggregation with Grouping

sum by (instance) (rate(http_requests_total[5m]))

Example: Alerting with PromQL

http_requests_total > 1000

Key PromQL Functions in Grafana

  • rate() - Calculates per-second rate over a time window
  • sum by() - Aggregates metrics by specified labels
  • up - Boolean metric indicating target health

4. Creating Dashboards

Example: Basic Dashboard Configuration

{
  "dashboard": {
    "title": "System Metrics Dashboard",
    "time": {
      "from": "now-1h",
      "to": "now"
    },
    "panels": [
      {
        "id": 1,
        "type": "graph",
        "title": "CPU Usage",
        "targets": [
          {
            "expr": "rate(node_cpu_seconds_total{mode!='idle'}[5m])"
          }
        ]
      }
    ]
  }
}
Property Description Values
dashboard.title Title of the dashboard string
dashboard.time.from Start time for the dashboard string
dashboard.time.to End time for the dashboard string
panels[].id Unique identifier for the panel number
panels[].type Type of panel (graph, table, etc.) string
panels[].title Title of the panel string
panels[].targets[].expr PromQL expression to query metrics string
Note: The time.from and time.to fields support relative time formats like now-1h.
Warning: Ensure that the PromQL expressions used in targets are valid and return data to avoid empty panels.

Dashboard Creation Steps

  • Create a new dashboard in Grafana UI or via API
  • Define the dashboard title and time range
  • Add panels with appropriate PromQL queries
  • Save the dashboard configuration

5. Implementing Template Variables

Example: Using Template Variables in Grafana Dashboard

{
  "panels": [
    {
      "title": "CPU Usage",
      "targets": [
        {
          "expr": "rate(node_cpu_seconds_total{job=\"$job\",instance=\"$instance\"}[5m])",
          "legendFormat": "{{cpu}}"
        }
      ]
    }
  ],
  "templating": {
    "list": [
      {
        "name": "job",
        "type": "query",
        "datasource": "Prometheus",
        "label": "Job",
        "query": "label_values(job)"
      },
      {
        "name": "instance",
        "type": "query",
        "datasource": "Prometheus",
        "label": "Instance",
        "query": "label_values(instance)"
      }
    ]
  }
}
Variable Name Type Description Usage Example
job query Query to fetch unique job values from Prometheus label_values(job)
instance query Query to fetch unique instance values from Prometheus label_values(instance)
Note: Template variables in Grafana allow dynamic filtering of data by substituting values at runtime. These are particularly useful for multi-environment dashboards.

Template Variable Configuration Options

  • Name: Unique identifier for the variable (e.g., job)
  • Type: Query, Text box, Constant, etc.
  • Datasource: Must be set to Prometheus for metric queries
  • Query: PromQL expression to fetch variable values
  • Label: Human-readable label for the dropdown in the dashboard

6. Using Exemplar Integration

Prometheus supports exemplar storage and retrieval, which allows associating trace IDs with metrics to enable deep-dive analysis in tools like Grafana.

Field Description Example
exemplar Exemplar data associated with a metric sample {trace_id="1234567890abcdef", span_id="0987654321fedcba"} 1.23

Example: Adding Exemplars to Metrics

package main

import (
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promauto"
)

var (
    httpRequestDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
        Name: "http_request_duration_seconds",
        Help: "Duration of HTTP requests in seconds",
    }, []string{"method", "endpoint"})
)

func main() {
    // Example of recording a metric with exemplar
    httpRequestDuration.WithLabelValues("GET", "/api/users").Observe(0.5)
}
Note: Exemplars are only supported in Prometheus 2.32+ and require a compatible storage backend.

Key Points

  • Exemplars provide trace context for metric samples.
  • They are stored in the same storage as metrics but with additional metadata.
  • Grafana can display exemplars when viewing time series data.

7. Configuring Alert Rules

Example: Basic Alert Rule Configuration

groups:
- name: example-group
  rules:
  - alert: HighRequestRate
    expr: rate(http_requests_total[5m]) > 100
    for: 2m
    labels:
      severity: page
    annotations:
      summary: "High request rate detected"
      description: "The request rate is {{ $value }} requests/second"
Field Description Required
alert Name of the alert rule Yes
expr PromQL expression that determines when the alert fires Yes
for Duration for which the condition must hold before firing No
labels Additional labels to attach to the alert No
annotations Additional information about the alert No
Note: The for field allows for alert staleness and prevents flapping.

Example: Alert with Multiple Conditions

groups:
- name: cpu-alerts
  rules:
  - alert: HighCPUUsage
    expr: (100 - (avg by(instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)) > 80
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: "High CPU usage on {{ $labels.instance }}"
      description: "CPU usage is at {{ $value }}%"

Example: Alert with Recording Rule

groups:
- name: recording-rules
  rules:
  - record: instance:requests_per_second
    expr: rate(http_requests_total[5m])
  - alert: HighRequestRate
    expr: instance:requests_per_second > 100
    for: 2m
    labels:
      severity: page

8. Implementing Annotations

Field Description Example
alertname Name of the alert InstanceDown
summary Short description of the alert Instance {{ instance }} is down
description Detailed explanation of the alert Instance {{ instance }} of job {{ job }} has been down for more than 5 minutes.
runbook_url URL to the runbook for this alert https://mycompany.com/runbooks/instance_down
dashboard_url URL to the dashboard related to this alert https://grafana.company.com/d/abc123/instance-metrics

Example: Annotation in Prometheus Rule

groups:
- name: example
  rules:
  - alert: InstanceDown
    expr: up == 0
    for: 5m
    labels:
      severity: page
    annotations:
      summary: "Instance {{ $labels.instance }} is down"
      description: "Instance {{ $labels.instance }} of job {{ $labels.job }} has been down for more than 5 minutes."
      runbook_url: "https://mycompany.com/runbooks/instance_down"
      dashboard_url: "https://grafana.company.com/d/abc123/instance-ms"
Note: Annotations are used in Grafana to provide additional context when viewing alerts or metrics. They can be added directly to alert rules in Prometheus.
Warning: Make sure that URLs in annotations are accessible from Grafana's environment to avoid broken links.

9. Using Explore Mode

Example: Querying metrics in Explore mode

up{job="prometheus"} == 1
Feature Description Usage
Explore Mode Interactive query interface for Prometheus Access via Grafana UI under "Explore"
Query Editor Real-time expression editor with syntax highlighting Type or paste PromQL expressions
Metrics Browser Lists available metrics and their labels Use to discover metric names and values
Time Range Selector Adjusts time window for queries Select from predefined ranges or custom times
Note: Explore mode supports PromQL and can visualize results as graphs, tables, or logs.

Explore vs. Dashboard Panels

  • Explore: For ad-hoc querying and exploration
  • Dashboard: For persistent visualization and alerting

10. Importing Community Dashboards

Community dashboards provide pre-built visualizations for popular systems like Kubernetes, Node.js, and databases. These can be imported into Grafana to accelerate monitoring setup.

Dashboard ID Source Description Tags
10000 Node Exporter System-level metrics for Linux hosts node-exporter, linux
13978 Kubernetes Cluster and pod-level metrics for Kubernetes kubernetes, cluster
9277 PostgreSQL Database performance and query statistics postgres, database

Example: Importing a Dashboard via UI

1. Navigate to Grafana UI
2. Go to Dashboards > Import
3. Enter Dashboard ID (e.g., 10000)
4. Select Prometheus data source
5. Click Import
Note: Ensure the Prometheus data source is configured and accessible before importing dashboards.
Warning: Some dashboards may require specific Prometheus metrics or labels that are not present in your setup.

11. Configuring Recording Rules in Grafana

Example: Recording Rule Configuration

groups:
- name: example_rules
  rules:
  - record: instance:cpu_usage:ratio
    expr: 1 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) / 100)
    labels:
      severity: critical
Property Description Example Value
name Name of the rule group example_rules
rules List of recording rules to define Array of rule objects
record Output metric name to create instance:cpu_usage:ratio
expr PromQL expression to evaluate 1 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) / 100)
labels Optional labels to attach to output metric {severity: critical}
Note: Recording rules are evaluated at the same interval as the evaluation_interval setting in Prometheus.
Warning: Ensure that the expr does not result in a large number of time series, which can cause performance issues.

12. Implementing Dashboard Provisioning

Example: Grafana Dashboard Configuration

apiVersion: 1

providers:
  - name: "prometheus"
    orgId: 1
    folder: ""
    type: "file"
    disableProvisioning: false
    options:
      path: "/etc/grafana/provisioning/dashboards"
Property Description Default
name Name of the provider None
orgId Organization ID to provision dashboards for 1
folder Folder to place dashboards in Empty string (root)
type Provisioning type (e.g., file, dashboard, json) None
disableProvisioning Disable provisioning if true false
options.path Path to dashboard files None
Note: Ensure the path specified in options.path is accessible to Grafana and contains valid JSON dashboard definitions.

Example: Dashboard JSON Definition

{
  "dashboard": {
    "title": "Prometheus Metrics Dashboard",
    "panels": [
      {
        "title": "CPU Usage",
        "targets": [
          {
            "expr": "rate(node_cpu_seconds_total[5m])"
          }
        ]
      }
    ]
  },
  "overwrite": true
}

Was this article helpful?