Created
December 5, 2021 13:48
-
-
Save whoisstan/0b43685ebd518518191319bb1b923fc9 to your computer and use it in GitHub Desktop.
Simple Express Logging Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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