2

I have installed log4js npm and try to implement logger to my node api... I am trying to use log4js for the first time. Code:

var log4js = require('log4js'); // include log4js

log4js.configure({ // configure to use all types in different files.
    appenders: [
        {   type: 'file',
            filename: "/logs/error.log", // specify the path where u want logs folder error.log
            category: 'error',
            maxLogSize: 20480,
            backups: 10
        },
        {   type: "file",
            filename: "/logs/info.log", // specify the path where u want logs folder info.log
            category: 'info',
            maxLogSize: 20480,
            backups: 10
        },
        {   type: 'file',
            filename: "/logs/debug.log", // specify the path where u want logs folder debug.log
            category: 'debug',
            maxLogSize: 20480,
            backups: 10
        }
    ]
});

var loggerinfo = log4js.getLogger('info'); // initialize the var to use.
var loggererror = log4js.getLogger('error'); // initialize the var to use.
var loggerdebug = log4js.getLogger('debug'); // initialize the var to use.

loggerinfo.info('This is Information Logger');
loggererror.info('This is Error Logger');
loggerdebug.info('This is Debugger');

I got error:

****throw new Error(`Problem with log4js configuration: (${util.inspect(config, { depth: 5 })})`
      ^
Error: Problem with log4js configuration: ({ appenders: 
   [ { type: 'file',
       filename: '/logs/error.log',
       category: 'error',
       maxLogSize: 20480,
       backups: 10 },
     { type: 'file',
       filename: '/logs/info.log',
       category: 'info',
       maxLogSize: 20480,
       backups: 10 },
     { type: 'file',
       filename: '/logs/debug.log',
       category: 'debug',
       maxLogSize: 20480,
       backups: 10 } ] }) - must have a property "appenders" of type object.****

I have run a log4js sample code in my application using cmd node log4js.js(this file name) Please help me...

Prabind
  • 21
  • 3

1 Answers1

0

I have this.

File name: myHelperlog4js.js

const { configure, getLogger } = require("log4js");
configure({
 appenders: {
     console: { type: 'console' ,"layout": { "type": "pattern", "pattern": "%d - %c:[%p]: %m" }},
     fileLog: { type: 'file', filename: '/logs/application.log' }
   },
   categories: {
     default: { appenders: ['console','fileLog'], level: 'trace' }, 
   }
 });

const logger = getLogger();
module.exports = {logger};

in your file to use, have this:

const {logger } = require('MY PAHT OF MY JS CONFIGURED/myHelperlog4js');

and for use only:

 logger.info(msg);
 logger.info(msg);
 logger.debug(msg);
 logger.info(msg);
 logger.warn(msg);
 logger.error(msg);
 logger.fatal(msg);
 logger.info(msg); 

 

/logs/application.log: save log in:

  • Windows (C:/logs/)
  • linux (/logs/)
Erik Roky
  • 111
  • 1
  • 5