Sunday, September 23, 2018

javascript - Node.js console.log() in txt file



I have another question (last question). At the moment i am working on a Node.js project and in this I have many console.log() functions. This has worked okay so far but I also want everything that's written to the console to also be written in a log-file. Can someone please help me?



For example:



Console.log('The value of array position [5] is '+ array[5]);


In my real code its a bit more but this should give you an idea.




Thank you hopefully.


Answer



I would use a library instead of re-inventing the wheel. I looked for a log4j-type library on npm, and it came up with https://github.com/nomiddlename/log4js-node



if you want to log to the console and to a file:



var log4js = require('log4js');
log4js.configure({
appenders: [

{ type: 'console' },
{ type: 'file', filename: 'logs/cheese.log', category: 'cheese' }
]
});


now your code can create a new logger with



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



and use the logger in your code



logger.warn('Cheese is quite smelly.');
logger.info('Cheese is Gouda.');
logger.debug('Cheese is not a food.');

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...