Skip to content

Instantly share code, notes, and snippets.

@VinayaSathyanarayana
Forked from pulkitsinghal/server.js
Created January 9, 2019 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VinayaSathyanarayana/2945e3b99ecbcdf27853f94a35b9095d to your computer and use it in GitHub Desktop.
Save VinayaSathyanarayana/2945e3b99ecbcdf27853f94a35b9095d to your computer and use it in GitHub Desktop.
Loopback Logging - intercept all HTTP responses, regardless of which middleware/route produced it
// Title:
// Loopback Logging - intercept all HTTP responses,
// regardless of which middleware/route produced it
// References:
// https://apidocs.strongloop.com/loopback/#app-middleware
// https://apidocs.strongloop.com/loopback/#app-middlewarefromconfig
// https://apidocs.strongloop.com/loopback/#app-definemiddlewarephases
//Sample # 1 - super simple
// If you would rather use middleware.json ... make sure to
// install this middleware among the first middleware,
// as it needs to hook into the response object before
// any other middleware sends back the response.
app.middleware('initial', function logResponse(req, res, next) {
// install a listener for when the response is finished
res.on('finish', function() {
// the request was handled, print the log entry
log(req.method, req.originalUrl, res.statusCode);
});
// resume the routing pipeline,
// let other middleware to actually handle the request
next();
});
//Sample # 2 - bit more advanced
// Also helps track reponse time for all URLs
app.middleware('initial', function logResponse(req, res, next) {
// http://www.senchalabs.org/connect/responseTime.html
var start = new Date;
if (res._responseTime) {
return next();
}
res._responseTime = true;
// install a listener for when the response is finished
res.on('finish', function() { // the request was handled, print the log entry
var duration = new Date - start;
log(req.method, req.originalUrl, res.statusCode, duration + 'ms', {
lbHttpMethod:req.method,
lbUrl:req.originalUrl,
lbStatusCode:res.statusCode,
lbResponseTime:duration
});
});
// resume the routing pipeline,
// let other middleware to actually handle the request
next();
});
//Sample # 3 - bit more focused
// Does work only for the API related URLs
app.middleware('initial', '/api/*', function logResponse(req, res, next) {
// same code as sample # 2
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment