1

I am trying to see if there is a way to access my logger form a request object. I have a cusotm winston wrapper that uses winston, express-winston, and moment to keep things clean across my apps.

In my app.js I just have

  var logger = require('winston-custom');

  server.use(logger());

Then in the controller I am trying to find a clean way to get the logger off the request object (if possible), so I do not have to import it here. My first guess was it's on the req.app, but it does not appear to be.

so In a controller for the same server I have

 function rootAPI(req, res) {
  console.log("req.app", req.app);

Which seems to not provide me with anything, I even tried logging req and digging through it. Is there any way to correctly achieve this? Thanks!

3
  • @dm03514 I can, I was asked to see if there is a way around this in passing it in the req object (if possible of course) Commented Jun 8, 2015 at 17:57
  • 1
    I mean, you could require it in your app and then in custom middleware attach it to the request, i just don't understand why you would do that instead of just requiring it. Commented Jun 8, 2015 at 17:58
  • @KevinB just requested to see if it could be done effectively, so just seeing if it's possible, thanks for the input! Commented Jun 8, 2015 at 18:31

2 Answers 2

2

If you're absolutely sure you need this functionality, you can achieve it by adding a custom field on request:

server.all("*", function(req, res, next)
{
    req.logger = logger;
    next();
});
Sign up to request clarification or add additional context in comments.

Comments

1

while the answer above is correct, we can simplify the implement by creating an express middleware:

const app = express()
const loggerMiddleware = (req, res, next) => { req.logger = logger; next()};
app.use(loggerMiddleware)

It is important that next() is called, else the next middleware wouldn't be called.

https://expressjs.com/en/guide/using-middleware.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.