TomFrost / Bristol

Insanely configurable logging for Node.js
MIT License
113 stars 19 forks source link

Child logger support #46

Open jeffijoe opened 6 years ago

jeffijoe commented 6 years ago

Loving Bristol, and have even written a target + formatter myself. 😄

It would be awesome to have support for child loggers! Imagine creating a child logger for each HTTP request, then set some globals for it (such as the calling user, request info, etc). It would share the transports, formatters and globals of it's parent.

Example API:

const logger = new Bristol({ ... })

app.use(authenticate())
app.use((ctx, next) => {
  const child = logger.createChildLogger({ /*additional config for child */ })

  child.setGlobal('user_id', () => ctx.state.user.id)
  ctx.logger = child
  return next()
})

app.use(get('/todos', (ctx) => {
  ctx.logger.info('Getting todos')
}))
jeffijoe commented 6 years ago

As a temporary trick to accomplish this:

/**
 * Creates a child logger from the specified parent.
 *
 * @param parentLogger
 */
export function createChildLogger(parentLogger) {
  const child = new Bristol()
  child.setSeverities(Object.keys(parentLogger._severities))
  child._targets = [...parentLogger._targets]
  child._transforms = [...parentLogger._transforms]
  child._globals = { ...parentLogger._globals }
  const getGlobals = child._getGlobals
  child._getGlobals = function() {
    return {
      ...parentLogger._getGlobals(),
      ...getGlobals.call(this)
    }
  }
  return child
}