Skip to content

Instantly share code, notes, and snippets.

@trojanh
Created July 1, 2021 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trojanh/bbdc466a9134ec5d72592c919985665f to your computer and use it in GitHub Desktop.
Save trojanh/bbdc466a9134ec5d72592c919985665f to your computer and use it in GitHub Desktop.
Grafana Prometheus Nodejs Integration Steps using prom-client
# Pre-requisite
Should have node >=12
# Install
npm i prom-client
# Setup
1. Create a Grafana.js file
//Grafana.js
```
import { collectDefaultMetrics, register } from 'prom-client'
async function initializeGrafana (_req, res) {
try {
res.set('Content-Type', register.contentType)
return res.end(await register.metrics())
} catch (err) {
return res.status(500).end(err)
}
}
export { collectDefaultMetrics, initializeGrafana }
```
2. Import Grafana in you server start file (usually server.js or app.js),
This is the file where your express app is first initialized
```
import { collectDefaultMetrics, initializeGrafana } from './Grafana'
// keep this on the top before initializing the express app
collectDefaultMetrics()
// place this right after `const app = new Express()`
app.get('/metrics', initializeGrafana)
```
3. Check response for `curl localhost:4001/metrics` from shell
You should see something like this if everything was done correctly
```
# HELP nodejs_gc_duration_seconds Garbage collection duration by kind, one of major, minor, incremental or weakcb.
# TYPE nodejs_gc_duration_seconds histogram
nodejs_gc_duration_seconds_bucket{le="0.001",kind="incremental"} 2
nodejs_gc_duration_seconds_bucket{le="0.01",kind="incremental"} 4
nodejs_gc_duration_seconds_bucket{le="0.1",kind="incremental"} 4
nodejs_gc_duration_seconds_bucket{le="1",kind="incremental"} 4
nodejs_gc_duration_seconds_bucket{le="2",kind="incremental"} 4
```
# Reference
https://grafana.com/oss/prometheus/exporters/nodejs-exporter/?tab=installation#introduction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment