Last active
March 21, 2018 06:21
-
-
Save krrrr38/3834c13e83c37782f4caa1bb5ffe202e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var Koa = require('koa'); | |
var Router = require('koa-router'); | |
var app = new Koa(); | |
var router = new Router(); | |
const instanceId = parseInt(process.env.NODE_APP_INSTANCE || 0); | |
const client = require('prom-client'); | |
client.collectDefaultMetrics(); | |
client.register.setDefaultLabels({ instanceId: instanceId }); | |
const appRequestSummary = new client.Summary({ | |
name: 'app_request', | |
help: 'app_request', | |
labelNames: ['method', 'name', 'type'], | |
percentiles: [0.5, 0.75, 0.90, 0.95, 0.99, 1.0] | |
}); | |
app.use(async (ctx, next) => { | |
const start = Date.now(); | |
await next().then(data => { | |
const ms = Date.now() - start; | |
const routeName = ctx._matchedRouteName || 'unknown'; | |
appRequestSummary.labels(ctx.method, routeName, 'success').observe(ms); | |
}).catch(err => { | |
const ms = Date.now() - start; | |
const routeName = ctx._matchedRouteName || 'unknown'; | |
appRequestSummary.labels(ctx.method, routeName, 'failure').observe(ms); | |
throw err; | |
}); | |
}); | |
router.get('index', '/', (ctx, next) => { | |
ctx.body = 'Hello Koa'; | |
}); | |
router.get('fail', '/fail', (ctx, next) => { | |
throw new Error("errorrrrrr"); | |
}); | |
// router.get('metrics', '/metrics', (ctx, next) => { | |
// ctx.set('Content-Type', client.register.contentType); | |
// ctx.body = client.register.metrics(); | |
// }); | |
app | |
.use(router.routes()) | |
.use(router.allowedMethods()); | |
const metricsPort = 9010 + instanceId; | |
console.log("start server: 3000, metrics server: " + metricsPort); | |
http.createServer((req, res) => { | |
res.setHeader('Content-Type', client.register.contentType); | |
res.write(client.register.metrics()); | |
res.end(); | |
}).listen(metricsPort); | |
app.listen(3000); |
Author
krrrr38
commented
Mar 21, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment