Skip to content

Instantly share code, notes, and snippets.

@whoisstan
Created December 5, 2021 13:48
Show Gist options
  • Save whoisstan/0b43685ebd518518191319bb1b923fc9 to your computer and use it in GitHub Desktop.
Save whoisstan/0b43685ebd518518191319bb1b923fc9 to your computer and use it in GitHub Desktop.
Simple Express Logging Middleware
//don't log tests
if (process.env.NODE_ENV !== 'test') {
app.use( (req, res, next) => {
//don't log OPTIONS calls
if (req.method !== 'OPTIONS' ) {
let startTime = Date.now();
res.on('finish', ()=> {
//sanitize and format query object
const query = Object.entries(req.query).map( v =>
`${v[0]}=${v[0]==='access-token'?'given':v[1]}`
).join("&")
const msg = `Http Request ${req.method} ${req.path} - ${res.statusCode} - ${Date.now() - startTime}ms - ${query}`
if(res.statusCode>=500){
logger.error(msg)
} else if(res.statusCode>=400){
logger.warn(msg)
} else {
logger[process.env.LOG_LEVEL || 'info'](message)
}
});
}
next();
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment