Tuesday, 13 August 2019

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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...