node.js - express logging response body -


the title should pretty self explanetory.

for debugging purposes, express print response code , body every request serviced. printing response code easy enough, printing response body trickier, since seems response body not readily available property.

the following not work:

var express = require('express'); var app = express();  // define custom logging format express.logger.format('detailed', function (token, req, res) {                                         return req.method + ': ' + req.path + ' -> ' + res.statuscode + ': ' + res.body + '\n'; });    // register logging middleware , use custom logging format app.use(express.logger('detailed'));  // setup routes app.get(..... omitted ...);  // start server app.listen(8080); 

of course, print responses @ client emitted request, prefer doing @ server side too.

ps: if helps, responses json, there solution works general responses.

not sure if it's simplest solution, can write middleware intercept data written response. make sure disable app.compress().

function logresponsebody(req, res, next) {   var oldwrite = res.write,       oldend = res.end;    var chunks = [];    res.write = function (chunk) {     chunks.push(chunk);      oldwrite.apply(res, arguments);   };    res.end = function (chunk) {     if (chunk)       chunks.push(chunk);      var body = buffer.concat(chunks).tostring('utf8');     console.log(req.path, body);      oldend.apply(res, arguments);   };    next(); }  app.use(logresponsebody); 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -