Reputation: 14216
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!
Upvotes: 1
Views: 1421
Reputation: 82
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
Upvotes: 1
Reputation: 7004
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();
});
Upvotes: 2