'How to make a proper logging in nodejs

I Have a service that uses wrapper class for Winston logger to log the HTTP calls, internal failers, and so on to be able to maintain the service on production

the behavior of logging is something like this

function getUser(req, res, next) {
  try {
    logger.info("user::api::getUser", "controller called");
    // do some stuff here, call the service related and return response
  } catch(err) {
     logger.error("user::api::getUser", err);
  }
}

and also this logger is called in all subsequent functions along with the app, such as services, db access layers, controllers, middlewares, and so on

Actually, I am disappointed about calling logger in each function I write which I feel like polluting the code and don't make single responsibility principle also makes the code violates closed to modification principle` since if I updated the logger API for example, then I have to go through all the functions that the logger used inside and update it to the new syntax which is not good

I thought about if I can use event-driven, I mean event emitters to emit events on each failure, call and the handlers of these events will write the appropriate log

for example something like this

function getUser(req, res, next) {
  try {
    eventEmitter("info", "controller called");
    // do some stuff here, call the service related and return response
  } catch(err) {
     eventEmitter.emit("error", err);
  }
}

and here is the listener

eventEmitter.on("error", (err) => {
  logger.error("error", err);
});

I see this syntax hides the implementation of calling the logger into one function instead of calling it in each part of the app, but still, the functions are polluted because I still have to call the event emitter inside them to emit logging event

I don't know if there is an intelligent way to implement logging without calling the logger in each part of the app like this !! Also, I am wondering how giant companies handle these cases in their applications

I hope someone respond to me and guide me to the right direction



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source