jeffijoe / awilix-express

Awilix helpers/middleware for Express
MIT License
114 stars 7 forks source link

Scoped logger per request? #13

Closed guumaster closed 6 years ago

guumaster commented 6 years ago

Is possible to have a scoped logger in a submodule used in the controller?

controller(scoped) => moduleA => moduleB.

I want to use a logger on moduleB scoped to the request (with traceId, correlation, etc). Is it possible? Thanks

jeffijoe commented 6 years ago

Yes it is, you register the preconfigured logger in a middleware that runs before your controller code. I do this for the same reason, contextual logging. 😄

jeffijoe commented 6 years ago

Here's an example. Include this before your controllers get resolved, and any module that gets resolved in that scope will receive that logger.

app.use((req, res, next) => {
  const logger = {
    log: (message) => {
      console.log(`${req.method} ${req.path}: ${message}`)
    }
  }

  req.container.register({
    logger: asValue(logger)
  })
  next()
})
talyssonoc commented 6 years ago

Thank you for the help, @jeffijoe!

guumaster commented 6 years ago

This works perfectly. Thanks!