1

I have created a logger object in utils/logger.js using the winston package. The entry-point for my project is index.js where I have const logger = require('./utils/logger'). How do I 'cascade' this logger object across all of project files (~20)? Should each file in my project also do a const logger = require('../utils/logger) ? If so, aren't they all individual logger objects when I do a node index.js?

I am using the following (from here) for utils.logger.js.

var appRoot = require('app-root-path');
var winston = require('winston');

// define the custom settings for each transport (file, console)
var options = {
  file: {
    level: 'info',
    filename: `${appRoot}/logs/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};

// instantiate a new Winston Logger with the settings defined above
var logger = new winston.Logger({
  transports: [
    new winston.transports.File(options.file),
    new winston.transports.Console(options.console)
  ],
  exitOnError: false, // do not exit on handled exceptions
});

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
  write: function(message, encoding) {
    // use the 'info' log level so the output will be picked up by both transports (file and console)
    logger.info(message);
  },
};

module.exports = logger;
cogitoergosum
  • 2,309
  • 4
  • 38
  • 62

1 Answers1

2

In my opinion, what you can do is create a function in the same file for logging and export those functions in your file, this way you'll be using the same object all over your project.

utils/logger.js



function InfoLogger(message){
logger.info(message);
}

module.exports = {InfoLogger}

Update: From the answer over here I learned that nodejs always uses 'require once' approach.

After you call require the first time, require uses a cache and will always return the same object.

I also tried this in the test project where I used console.log in the start of file and exported a function from the file. Then imported the function multiple times in my project and the console.log only ran once.

So your var logger = will only run once and you're sharing the same object

ibrahimijc
  • 331
  • 3
  • 12
  • However, upon `require('../utils/logger.js')`, the `var logger =` is executed. This means, the `logger` object is created every time. How do I create the `logger` object only once and share across the project? – cogitoergosum Jul 06 '20 at 03:07
  • 1
    Not exactly, because require only instantiates once the exported variable is shared among all "requiring" functions. Just ran a test for myself with a log to check if the logger.js create is run twice,and it only ran once, as expected :) – Doug Dec 13 '20 at 16:12