-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (63 loc) · 1.75 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import express from 'express';
import responseTime from 'response-time';
import { collectDefaultMetrics, register, Histogram, Counter } from 'prom-client';
import { createLogger, transports } from "winston";
import LokiTransport from "winston-loki";
import { heavyTask } from './util.js';
const options = {
transports: [
new LokiTransport({
labels:{
appName:"express"
},
host: "http://localhost:3100"
})
]
};
const logger = createLogger(options);
const app = express();
const PORT = process.env.PORT || 8000;
collectDefaultMetrics();
const reqResTime = new Histogram({
name: 'http_express_req_res_time',
help: 'Request response time',
labelNames: ['method', 'route', 'status_code'],
buckets: [1, 50, 100, 200, 400, 500, 800, 1000,2000]
});
const totalRequestCounter = new Counter({
name: 'total_req',
help: 'Tells total request'
});
app.use(responseTime((req, res, time) => {
if (!req.headers['user-agent']?.includes('Prometheus')) {
totalRequestCounter.inc();
}
reqResTime.labels({
method: req.method,
route: req.url,
status_code: res.statusCode
}).observe(time);
}
));
app.get('/', (req, res) => {
logger.info("Req came on /");
res.json({ message: 'Hello World!' });
});
app.get('/slow', async (req, res) => {
try {
logger.info("Req came on /slow");
const result = await heavyTask();
return res.json(result);
} catch (err) {
logger.error(JSON.stringify(err));
return res.status(500).json(err);
}
});
app.get('/metrics', async (req, res) => {
res.set('Content-Type', register.contentType);
const metrics = await register.metrics();
res.end(metrics);
});
app.listen(PORT, () => {
console.log(`App listening at http://localhost:${PORT}`);
});