Skip to content

Adding raw metrics

Course: Prometheus and Grafana - chapter 3

Lets build an express app that exports metrics

Section titled “Lets build an express app that exports metrics”

Let’s add some hand made metrics to an express app

  • Initialize a TS project
npm init -y
npx tsc --init
  • Replace rootDir and outDir
"rootDir": "./src",
"outDir": "./dist",
  • Add dependencies
npm install express @types/express
  • Create src/index.ts
import express from "express";
const app = express();
app.use(express.json());
app.get("/user", (req, res) => {
res.send({
name: "John Doe",
age: 25,
});
});
app.post("/user", (req, res) => {
const user = req.body;
res.send({
...user,
id: 1,
});
});
app.listen(3000);
  • Create a middleware that tracks the total time to handle a request (middleware.ts)
import { NextFunction, Request, Response } from "express";
export const middleware = (req: Request, res: Response, next: NextFunction) => {
const startTime = Date.now();
next();
const endTime = Date.now();
console.log(`Request took ${endTime - startTime}ms`);
}
  • Add the middleware globally
app.use(middleware);
  • Update package.json to add scripts
"scripts": {
"build": "tsc -b",
"start": "npm run build && node dist/index.js"
},
  • Run the application
npm run start
  • Try to send a request and notice the logs