Skip to content

Instantly share code, notes, and snippets.

@cgutwin
Created July 2, 2019 22:02
Show Gist options
  • Save cgutwin/c1210a98247c153e3ab431b026d3a758 to your computer and use it in GitHub Desktop.
Save cgutwin/c1210a98247c153e3ab431b026d3a758 to your computer and use it in GitHub Desktop.
An Express middleware function to log incoming HTTP requests, with basic formatting of objects.
/*
* Will accept an object, and add a carriage return to the end of each entry
* to format for console readability.
* */
const formatObject = (obj) => {
let formattedObject = ``
/*
Some items might come in empty (such as params, query, body), so if it's
empty, just skip over it.
Also double check the item is an object, as the recursion can't check when
called.
*/
if (
typeof obj === 'object' &&
obj !== null &&
Object.keys(obj).length
) {
formattedObject += `{`
for (const [key, value] of Object.entries(obj)) {
// Run again on nested entries
formattedObject += `\r\n ${key}: ${formatObject(value)}`
}
formattedObject += `\r\n}`
}
// If it gets skipped over, just return the original object as a string.
else formattedObject = JSON.stringify(obj)
return formattedObject
}
export default (req, res, next) => {
let logMessage = `Request recieved: \r\n`
const entriesToLog = [
'headers',
'url',
'method',
'statusCode',
'params',
'query',
'body'
]
entriesToLog.map(entry => {
let entryToLog = req[entry]
if (typeof entryToLog === 'object') entryToLog = formatObject(entryToLog)
logMessage += `${entry}: ${entryToLog}\r\n`
})
console.log(`${logMessage} \r---------------------------`)
next()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment