var express = require('express');
var router = express.Router();
var fs = require('fs');
var profiler = require('nodegrind');
router.get('/', function(req, res) {
// filename
var name = (new Date().getTime()) + '.cpuprofile';
// Start to measure
profiler.startCPU(name);
// Stop to measure after 5 sec
setTimeout(function(){
var cpuProfile = profiler.stopCPU(name, 'cpuprofile');
//Write profile
fs.writeFile(name, cpuProfile, function(err){
if (err) res.send(err);
else res.send('OK:' + name);
});
}, 5000);
});
module.exports = router;
routes/snapheap.js
var express = require('express');
var router = express.Router();
var fs = require('fs');
var heapdump = require('heapdump');
router.get('/', function(req, res) {
// filename
var name = (new Date().getTime()) + '.heapsnapshot';
// Take a snapshot of heap
heapdump.writeSnapshot(name, function() {
res.send('OK:' + name);
});
});
module.exports = router;
ルーティングの設定
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var snapcpu = require('./routes/snapcpu');
var snapheap = require('./routes/snapheap');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/snapcpu', snapcpu);
app.use('/snapheap', snapheap);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
$ for i in `seq 5`; do curl 'http://127.0.0.1:3000/'; sleep 1s; done
$ curl http://127.0.0.1:3000/snapheap
OK:1409475822884.heapsnapshot
$ ls
1409475822884.heapsnapshot app.js bin node_modules package.json public routes views
CPU使用率のスナップショット
$ for i in `seq 10`; do curl 'http://127.0.0.1:3000'; sleep 1s; done
# Do following command during for loop
$ curl http://127.0.0.1:3000/snapcpu
$ ls
1409475822884.heapsnapshot 1409477190566.cpuprofile app.js bin node_modules package.json public routes views