configuring custom logger #19
-
If I configure a custom logger, does it get passed into the request object? Is it possible for me to pass it on down from the controller to the service or do I need to handle logging from my business logic differently? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
It does not get passed to request object by default. There are two ways you could use your logger in controllers: Solution 1Export an instanciated logger, instead of the // logger.js
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
new winston.transports.Console({
format: winston.format.simple(),
})
]
});
module.exports = logger; Then you can import that logger in your controllers file whenever you need it: // controller.js
const logger = require('./logger.js');
module.exports.controller = function someController(req, res) {
logger.info("Log some info");
/* Controller logic */
} Solution 2Create a simple middleware function that inserts the logger in the request object: // index.js
const logger = require("./logger.js");
const middleware = (req, _res, next) => { req.logger = logger; next() }
oasTools.use(middleware, authCfg, 0);
oasTools.initialize(app).then(() => ...) Then you can access // controller.js
module.exports.controller = function someController(req, res) {
req.logger.info("Log some info");
/* Controller logic */
} |
Beta Was this translation helpful? Give feedback.
It does not get passed to request object by default. There are two ways you could use your logger in controllers:
Solution 1
Export an instanciated logger, instead of the
winston.createLogger
function:Then you can import that logger in your controllers file whenever you need it: