Open realhidden opened 8 years ago
With a few small modification this plugin can be compatible with morgan logging.
Take this example code:
var apirouter = express.Router(); apirouter.use(morgan('dev')); apirouter.use(function (req, res, next) { res.json({magic:true}); }); app.use('/api',apirouter);
This outputs:
post /user - - ms - - post /user - - ms - -
But with a "small" middleware:
var apirouter = express.Router(); apirouter.use(function(req,res,next){ if (typeof res.socket == 'undefined') { res.socket = { writable: true }; res.__onFinished={ queue: [] }; res._header = { status: 200 }; res.getHeader = function(type){ return res._header[type]; }; res.finished = false; res.writeHead = function(){ res.statusCode = res._header.status; res.__onFinished.queue[0](); }; var oldSendStatus = res.sendStatus; res.sendStatus = function (status){ res._header['status'] return oldSendStatus(status); } var oldsend = res.send; res.end = res.send = res.json = function(data){ if (typeof data != 'string'){ res._header['content-length'] = JSON.stringify(data).length; }else{ res._header['content-length'] = data.length; } res.writeHead(); return oldsend.apply(this, arguments); } } return next(); }); apirouter.use(morgan('dev')); apirouter.use(function (req, res, next) { res.json({magic:true}); }); app.use('/api',apirouter);
Morgan logging is fixed:
post /user 200 0.731 ms - 14 post /user 200 0.115 ms - 14 post /user 200 0.063 ms - 14 post /user 200 0.313 ms - 14
Very nice, thanks for sharing! It would definitely be useful to have loggers etc work out of the box. PR's are welcome! :) PS. Looks like you've forgot to assign res._header['status'] in sendStatus().
res._header['status']
sendStatus()
With a few small modification this plugin can be compatible with morgan logging.
Take this example code:
This outputs:
But with a "small" middleware:
Morgan logging is fixed: