0

I am trying to write a generic log function that will accept string and object type of arguments of variable length and print them with some metadata related to the modules and sub modules. But I can't figure out a way print all the arguments together. Currently I am doing this.

// MODULE_NAME is different for every module of my project, so
// that I know which module the log belongs to.

function myLogger() {
  for (var i = 0; i < arguments.length; i++) {
    console.log(MODULE_NAME, ":", arguments[i]);
  }
}

I am looking for a better way to do it which will work for following examples.

// MODULE_NAME = "TEST"
myLogger("error");
myLogger("error", err, ", result", res);
myLogger("hello", "world");

Output of the above calls should be

TEST : error
TEST : error {obj}, result {obj} 
TEST : hello world
1
  • 1
    You could use join to join them. Commented Aug 8, 2017 at 7:26

2 Answers 2

2

console.log actually accepts variadic arguments. You can do something like

function myLogger(...args) {
  console.log(MY_MODULE, ...args);
}

to pass all the arguments directly into console.log.

If your life company sucks and you can't use modern JS (with a transpiler), you can use .apply()

function myLogger() {
  console.log.apply(console, [MY_MODULE].concat(arguments));
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works for me I. I am using latest version for JS :D . Thanks mate !
-1

You can use winston logger.Through which you can generate five different level of logs. Please see my code below:

const winston = require('winston');
const fs = require('fs');
const env = process.env.NODE_ENV || 'development';
const logDir = 'log';
// Create the log directory if it does not exist
if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir);
}
const tsFormat = () => (new Date()).toLocaleTimeString();
const logger = new(winston.Logger)({
    transports: [
        // colorize the output to the console
        new(winston.transports.Console)({
            timestamp: tsFormat,
            colorize: true,
            level: 'info'
        }),
        new(require('winston-daily-rotate-file'))({
            filename: `${logDir}/-results.log`,
            timestamp: tsFormat,
            datePattern: 'yyyy-MM-dd',
            prepend: true,
            level: env === 'development' ? 'verbose' : 'info'
        })
    ]
});
 logger.debug('Debugging info');
 logger.verbose('Verbose info');
 logger.info('Hello world');
 logger.warn('Warning message');
 logger.error('Error info');

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.