-
Notifications
You must be signed in to change notification settings - Fork 802
/
server.js
67 lines (56 loc) · 1.89 KB
/
server.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
const Prometheus = require('prom-client')
const express = require('express');
const http = require('http');
Prometheus.collectDefaultMetrics();
const requestHistogram = new Prometheus.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['code', 'handler', 'method'],
buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5]
})
const requestTimer = (req, res, next) => {
const path = new URL(req.url, `http://${req.hostname}`).pathname
const stop = requestHistogram.startTimer({
method: req.method,
handler: path
})
res.on('finish', () => {
stop({
code: res.statusCode
})
})
next()
}
const app = express();
const server = http.createServer(app)
// See: http://expressjs.com/en/4x/api.html#app.settings.table
const PRODUCTION = app.get('env') === 'production';
// Administrative routes are not timed or logged, but for non-admin routes, pino
// overhead is included in timing.
app.get('/ready', (req, res) => res.status(200).json({status:"ok"}));
app.get('/live', (req, res) => res.status(200).json({status:"ok"}));
app.get('/metrics', async (req, res, next) => {
const metrics = await Prometheus.register.metrics();
res.set('Content-Type', Prometheus.register.contentType)
res.end(metrics);
})
// Time routes after here.
app.use(requestTimer);
// Log routes after here.
const pino = require('pino')({
level: PRODUCTION ? 'info' : 'debug',
});
app.use(require('pino-http')({logger: pino}));
app.get('/', (req, res) => {
// Use req.log (a `pino` instance) to log JSON:
req.log.info({message: 'Hello from Node.js Starter Application!'});
res.send('Hello from Node.js Starter Application!');
});
app.get('*', (req, res) => {
res.status(404).send("Not Found");
});
// Listen and serve.
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`App started on PORT ${PORT}`);
});