Commit 1e3d89f1 authored by Jarrod's avatar Jarrod 💬

Initial commit after detachment

parents
Pipeline #3308 failed with stages
in 0 seconds
node_modules
# @nahanil/sails-hook-apilog
Terse request logging for Sails.js applications.
Forked from Mike McNeil's pretty awesome [sails-hook-apianalytics](https://github.com/sailshq/sails-hook-apianalytics).
module.exports = require('./lib/sails-hook-api-log')
/**
* Module dependencies
*/
const _ = require('@sailshq/lodash')
/**
* Track an API request.
*/
module.exports = function logRequest (req, res, next) {
// Get access to app instance
const sails = req._sails
// Basic route information
const report = {
path: req.path,
method: req.method,
protocol: req.protocol,
ip: req.protocol === 'ws' ? req.ip || req.socket.handshake.address : req.ip,
diagnostic: {}
}// </build initial report>
// Track when this was received.
const receivedAt = Date.now()
// If `req._startTime` exists and is valid, then compute and include `middlewareLatency` in our report.
// (Otherwise don't include middlewareLatency, since it'd be meaningless.)
if (_.isNumber(req._startTime)) {
report.diagnostic.middlewareLatency = receivedAt - req._startTime
}// >-
// Call `onRequest` function
if (_.isFunction(sails.config['api-log'].onRequest)) {
sails.config['api-log'].onRequest(report, req, res)
}// >-
// Now bind a one-time listener that will fire when the request is finished.
res.once('finish', function onceFinish () {
// Track when the response finished.
const finishedAt = Date.now()
// Compute and track total response time
// (ms since request was received here and when the response finished, + any middleware latency, if known)
report.responseTime = (
(finishedAt - receivedAt) +
(report.diagnostic.middlewareLatency || 0)
)
// Add response status code to the report.
report.statusCode = +res.statusCode
// Call log function
if (_.isFunction(sails.config['api-log'].onResponse)) {
sails.config['api-log'].onResponse(report, req, res)
}
})// </bind one-time listener for `finish` event :: i.e. res.once()>
// Pass control on to app
return next()
}
/**
* Module dependencies
*/
const util = require('util')
const _ = require('@sailshq/lodash')
const logRequestWare = require('./private/log-request.middleware')
/**
* Based on sails-hook-apianalytics
*/
module.exports = function sailsHookApiLog (sails) {
function pad (n) { return n < 10 ? '0' + n : n }
function getAPILogTimestamp (date) {
return util.format(
'%s-%s-%s %s:%s:%s.%s',
date.getFullYear(),
pad(date.getMonth()),
pad(date.getDate()),
pad(date.getHours()),
pad(date.getMinutes()),
pad(date.getSeconds()),
pad(date.getMilliseconds())
)
}
return {
/**
* Default configuration for hook, you can override these on your own config file if needed.
*/
defaults: {
'api-log': {
routesToLog: [
'GET r|^((?![^?]*\\/[^?\\/]+\\.[^?\\/]+(\\?.*)?).)*$|',
// (^^Leave out assets)
'POST /*',
'PATCH /*',
'PUT /*',
'DELETE /*'
],
// TODO: This is actually a good feature. > Why is it gone?
// dontLogParams: [
// 'password',
// 'token'
// ],
onRequest: function (/* report, req, res */) {
// Defaults to doing nothing
},
// When response has finished...
onResponse: function (report, req /*, res */) {
try {
// The log function to use.
const logFn = console.log
// Build final, formatted output.
const formattedOutput = util.format(
'%s request: [%s] {%s} %s %s %s - %s',
getAPILogTimestamp(new Date()),
report.ip,
req.me ? req.me.id : req.user ? req.user.id : '',
report.statusCode,
report.method,
report.path,
report.responseTime
)
// Now log it.
logFn(formattedOutput)
} catch (e) {
// If an unhandled error occurs, dump it to the terminal.
// (but don't let it crash the process!)
sails.log.error('Consistency violation: `@nahanil/sails-hook-api-log hook` encountered an unexpected error when attempting to log information about an incoming request. Details:', e)
}// >-•
// All done.
}// </default `sails.config['api-log'].onResponse` notifier>
}// </definition of default `sails.config['api0log']` dictionary>
}, // </defaults>
/**
* Method that runs automatically when the hook initializes itself.
*
* @param {Function} next Callback function to call after all is done
*/
initialize: function initialize (next) {
sails.log.info('Initializing `api-log` hook... (requests to monitored routes will be logged!)')
// Listen for when the router in Sails says it's time to bind "before" shadow routes:
sails.on('router:before', function routerBefore () {
_.each(sails.config['api-log'].routesToLog, function iterator (routeAddress) {
sails.router.bind(routeAddress, logRequestWare)
})
})// </bind router:before event>
// Define a property we'll use to keep track of the last time
// this hook finished handling a response (or in this case, when
// this hook was initialized). We use this to be able to write
// date/time "landmarks" to the terminal.
sails.hooks['api-log']._lastResponseFinishedAt = Date.now()
return next()
}// </initialize>
}
}
{
"name": "@nahanil/sails-hook-apilog",
"version": "1.0.0-alpha.1",
"description": "Terse Sails.js request logging middleware",
"main": "index.js",
"directories": {
"lib": "lib"
},
"scripts": {
"lint": "standard",
"test:unit": "echo \"There are no tests specified\"",
"test": "npm run lint && npm run test:unit"
},
"repository": {
"type": "git",
"url": "https://git.carrotlabs.net/jarrod/sails-hook-apilog.git"
},
"keywords": [
"sails.js",
"log",
"logging",
"middleware"
],
"author": "Jarrod Linahan <jarrod@linahan.id.au>",
"license": "MIT",
"devDependencies": {
"standard": "^14.3.1"
},
"sails": {
"isHook": true
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment