Skip to content

Commit

Permalink
Avoid to log if the log is not set (#776)
Browse files Browse the repository at this point in the history
  • Loading branch information
allevo authored and mcollina committed Feb 28, 2018
1 parent eb24aa7 commit f545acc
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions fastify.js
Expand Up @@ -34,19 +34,23 @@ function validateBodyLimitOption (bodyLimit) {
}
}

function noop () { }

function build (options) {
options = options || {}
if (typeof options !== 'object') {
throw new TypeError('Options must be an object')
}

var log
var hasLogger = false
if (isValidLogger(options.logger)) {
log = loggerUtils.createLogger({
logger: options.logger,
serializers: Object.assign({}, loggerUtils.serializers, options.logger.serializers)
})
} else if (!options.logger) {
hasLogger = true
log = Object.create(abstractLogging)
log.child = () => log
} else {
Expand All @@ -72,7 +76,7 @@ function build (options) {
const genReqId = customGenReqId || loggerUtils.reqIdGenFactory()
const now = loggerUtils.now
const onResponseIterator = loggerUtils.onResponseIterator
const onResponseCallback = loggerUtils.onResponseCallback
const onResponseCallback = hasLogger ? noop : loggerUtils.onResponseCallback

const app = avvio(fastify, {
autostart: false
Expand Down Expand Up @@ -195,16 +199,19 @@ function build (options) {
return fastify

function routeHandler (req, res, params, context) {
res._context = context
req.id = genReqId(req)
req.log = res.log = log.child({ reqId: req.id, level: context.logLevel })
req.originalUrl = req.url

req.log.info({ req }, 'incoming request')

res._startTime = now()
res.on('finish', onResFinished)
res.on('error', onResFinished)
res._startTime = hasLogger ? now() : undefined

if (hasLogger === false || context.onResponse !== null) {
res._context = context
res.on('finish', onResFinished)
res.on('error', onResFinished)
}

if (context.onRequest !== null) {
runHooks(
Expand Down

0 comments on commit f545acc

Please sign in to comment.