Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write logs in file using log4js in node js

my code is:

log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('logs/cheese.log'), 'cheese');
logger.setLevel('DEBUG');

logger.trace('Entering cheese testing');
logger.debug('Got cheese.');
logger.info('Cheese is Gouda.');
logger.warn('Cheese is quite smelly.');
logger.error('Cheese is too ripe!');
logger.fatal('Cheese was breeding ground for listeria.');

it's creating a file named as 'cheese' but nothing is there inside that. How to write content in that?

like image 854
Mahendra Avatar asked Mar 14 '14 09:03

Mahendra


People also ask

What is Log4js in node js?

This is a conversion of the log4js framework to work with node. I started out just stripping out the browser-specific code and tidying up some of the javascript to work better in node. It grew from there.


2 Answers

This solution helps u create logs folder and three files error.log,debug.log and info.log in ur folder log with the logs. Worked for me. Thanks.

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');
like image 172
Vaibhav Magon Avatar answered Oct 09 '22 13:10

Vaibhav Magon


In the above code you are missing logger declaration : Add the line var logger = log4js.getLogger('cheese');

The whole block of code will be as follows:

var log4js = require('log4js');

log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('logs/cheese.log'), 'cheese');

var logger = log4js.getLogger('cheese');

logger.setLevel('DEBUG');
logger.trace('Entering cheese testing');
logger.debug('Got cheese.');
logger.info('Cheese is Gouda.');
logger.warn('Cheese is quite smelly.');
logger.error('Cheese is too ripe!');
logger.fatal('Cheese was breeding ground for listeria.');

Reference

like image 21
Hridya Avatar answered Oct 09 '22 13:10

Hridya